You can run a script when starting a Docker container by using the CMD or ENTRYPOINT directives in your Dockerfile. Here’s a simple example using CMD:
```
FROM ubuntu:18.04
RUN mkdir /app
COPY script.sh /app/script.sh
RUN chmod +x /app/script.sh
CMD [“/app/script.sh”]
```
This Dockerfile does the following steps:
- Pulls the ubuntu:18.04 base image.
- Creates an /app directory within the container.
- Copies a local file named script.sh to /app/script.sh inside the container.
- Changes the permissions of the script to make it executable.
- When the Docker container runs, it executes /app/script.sh.
Please note:
- The primary purpose of CMD is to tell the container which command it should run when it is started.
- The ENTRYPOINT command and CMD instruction can be used interchangeably in dockerfile as they serve similar purpose, with some minor differences.
Remember to replace `script.sh` with your actual script. After these steps when you build and run this Docker container, the CMD directive will execute your script.
Build the Docker image by running the following command:
```
docker build -t your_image_name .
```
Start the container from this image:
```
docker run your_image_name
```