Introduction - Why Copy a Docker Container?

For today’s blog, I will explain the utility of copying an existing docker container into an image for later use. Let’s say that you have a pre-existing docker container that you assigned port forwardings to in the past. Let’s also say, for argument’s sake, that you want to keep that pre-existing container the way it is, but you want to make another instance of that container that has additional forwarded (is that a word?) ports for future use. This guide is for you.

Using Docker Commit to Create an Image

To start off, let’s begin by stating an important fact: the only time in a docker container’s lifespan in which you can forward ports is with the use of the docker run command. Commands such as docker start cannot use the -p option in order to add additional ports.

To circumvent this issue, we must use the commit docker command to create a new image from a container’s changes. (from the words of docker help commit itself) In order to see the containers (whether they are running or not), use the Docker command docker ps -a, as shown below. docker ps -a

Following this, we need to commit the container. For our example, we will use the simple-prometheus container pictured above. The syntax will be docker commit name-of-original name-of-new as pictured below. docker commit

Creating a New Container from an Image

Now that we have an image of the original container simple-prometheus, we can use that image to create a brand new container using the same old run command we all know and love, this time with the port we wanted to forward. We will forward port 3060 on the new container. testcon1

To verify that the container has been properly run, we will run a standard docker ps -a and look at our images. Sure enough, testcon1 is present! testcon

And that’s it! If neccessary, you can stop the previously running container by using docker stop container-name-here. Happy port forwarding~