How to commit changes to a Docker image

By

Learn how to save the state of a running container as a new tagged Docker image with the docker commit command, adding messages and config changes.

~~~

To commit changes to a Docker image, use the docker commit command. It takes the current state of a running container, filesystem changes included, and saves it as a new image you can tag, run, and push.

Say you deployed your app, then fixed a bug inside the container, or installed a missing package. docker commit lets you snapshot that state as a new version of the image.

Find the container ID

First get the ID of the running container:

docker ps

The first column of the output is the container ID. You don’t need the full ID, the first few characters are enough as long as they identify the container uniquely.

Create the new image

Then use docker commit to create a new tagged image from it:

docker commit <id> <username>/<imagename>:<tagname>

For example:

docker commit 6a3f8c297cf6 flaviocopes/examplenode:1.1

Run docker images and you’ll see the new image listed, ready to be started with docker run or pushed to a registry.

You can add a message describing what changed with -m, and set the author with -a:

docker commit -m "install curl" -a "Flavio Copes" 6a3f8c297cf6 flaviocopes/examplenode:1.1

The message shows up when you inspect the image with docker history.

Changing the image configuration

The --change (or -c) flag applies a Dockerfile instruction to the new image. Use it to change the startup command, add an environment variable, expose a port, and so on:

docker commit --change 'ENV NODE_ENV=production' 6a3f8c297cf6 flaviocopes/examplenode:1.2

The supported instructions are CMD, ENTRYPOINT, ENV, EXPOSE, LABEL, ONBUILD, USER, VOLUME and WORKDIR.

Two things to watch out for

By default Docker pauses the container while the commit runs, so the filesystem is captured in a consistent state. If you can’t afford the pause, pass --pause=false, accepting the risk of catching files mid-write.

Data stored in volumes is not included in the commit. A volume lives outside the container’s filesystem, so a committed image won’t contain your database files or uploaded content.

One last piece of advice: treat docker commit as a snapshot tool, great for debugging or saving an experiment. For releases, update the Dockerfile and rebuild instead. An image built from a Dockerfile documents every step that produced it. A committed image doesn’t tell you how it was made.

Tagged: Docker · All topics
~~~

Related posts about docker: