Commit container changes with new CMD and EXPOSE instructions
In this final step, we will learn how to commit container changes and set the default command (CMD
) and exposed ports (EXPOSE
) for the new image.
The CMD
instruction sets the default command that will be executed when a container is started from the image without specifying a command. The EXPOSE
instruction informs Docker that the container listens on the specified network ports at runtime.
We will commit the my-ubuntu
container again, this time setting a default command to print the content of /hello.txt
and exposing port 80.
First, ensure the my-ubuntu
container is stopped.
docker stop my-ubuntu
Now, commit the container with the CMD
and EXPOSE
instructions. Note that the CMD
instruction is provided as a JSON array of strings.
docker commit -c 'CMD ["cat", "/hello.txt"]' -c 'EXPOSE 80' my-ubuntu my-ubuntu-final
You should see the ID of the newly created image as output.
Let's verify the CMD
and EXPOSE
configurations of the new image my-ubuntu-final
using docker inspect
.
docker inspect --format '{{.Config.Cmd}}' my-ubuntu-final
This should output [cat /hello.txt]
, confirming the default command is set.
Now, let's check the exposed ports.
docker inspect --format '{{.Config.ExposedPorts}}' my-ubuntu-final
You should see output similar to map[80/tcp:{}]
, indicating that port 80 is exposed.
Finally, let's run a container from this new image without specifying a command to see if the default CMD
works.
docker run --rm my-ubuntu-final
The --rm
flag automatically removes the container when it exits. Since the default command is cat /hello.txt
, the container should run, print "Hello from inside the container!", and then exit.
You should see "Hello from inside the container!" printed to your terminal.
This demonstrates how you can commit container changes and define the default behavior and network configuration of the resulting image.