Run a command line when starting a docker container

Viewed 2887

As far as I'm concerned you can run a command line when building an image with RUN or when running a container with CMD. Is there anyway to do so when starting a docker container?

My goal is to run the gcloud datastore automatically just after typing docker start my_container_name.

If this is possible, which changes should I apply to my Dockerfile?

(I have already installed all the packages required and I can run that command after docker run --name my_container_name -i -t my_image_name but I want it to be run also when starting the container)

1 Answers

Docker execute RUN command when you build the image.

Docker execute ENTRYPOINT command when you start the container. CMD goes as arguments to ENTRYPOINT. Both of these can be overridden when you create a container from an image. Their purpose in Dockerfile is to provide defaults for future when you or someone else will be creating containers from this image.

Consider the example:

FROM debian:buster

RUN apt update && apt install procps

ENTRYPOINT ["/usr/bin/ps"]
CMD ["aux"]

The RUN command adds ps command to the image, ENTRYPOINT and CMD are not executed but they will be when you run the container:

# create a container named 'ps' using default CMD and ENTRYPOINT
docker run --name ps my_image
# equivalent to /usr/bin/ps aux

# start the existing container 'ps'
docker start ps
# equivalent to /usr/bin/ps aux

# override CMD
docker run my_image au
# equivalent to /usr/bin/ps au

# override both CMD and ENTRYPOINT
docker run --entrypoint=/bin/bash my_image -c 'echo "Hello, world!"'
# will print Hello, world! instead of using ps aux

# no ENTRYPOINT, only CMD
docker run --entrypoint="" my_image /bin/bash -c 'echo "Hello, world!"'
# the output is the same as above

Each time you use docker run you create a container. The used ENTRYPOINT and CMD are saved as container properties and executed each time you start the container.

Related