How do I create a Docker image from a container without configuration changes?

HOW TO -️ October 18, 2021

I am aware of two ways of creating Docker images:

  1. Build the image using a Dockerfile
  2. Use docker commit <container_id> against a running container with changes.

I find changing a Dockerfile each time I need image changes to be awfully inconvenient. Instead I have taken to launching ephemeral containers with docker run, installing packages I need on the fly with sudo, then committing the image.

I didn't realize however there is a footgun involved in this approach, especially if you frequently use and switch up docker run hacks. I launch containers with changing bind mounts, environment variables, differing networks, etc. A lot of that seems to be considered part of the configuration of the container, and is committed in docker commit alongside actual filesystem changes.

For example if you do:

ERROR Rendering Code Block

You will see that the env variable FOO is now a part of new_image.

This creates some awfully confusing situations, as I consider arguments to docker run to be as ephemeral as the container it creates. I am only concerned about persisting package installs.

I would like to commit just the actual image, just the file system changes. Is there any way to do that?


The way to go is as you said to write a Dockerfile. Why do you find it inconvenient? It should be roughly just adding some RUN ... directives similar to what you do manually when running the initial container. This has been answered in another thread: