Updating a deployed container based on a Docker image

By

Learn how to update a deployed Docker container after the image changes on Docker Hub: stop, remove, pull, and rerun it, or automate it with Watchtower.

~~~

To update a deployed container after the image changed on Docker Hub, you stop and remove the running container, pull the new image, and start a fresh container from it. There is no in-place upgrade.

Why? A container is created from a specific version of an image, and it keeps running that version forever. Pulling a newer image doesn’t touch existing containers. Containers are meant to be disposable: you throw the old one away and create a new one.

The manual steps

First you stop the container:

docker stop <ID or name>

Then you remove the container:

docker rm <ID or name>

Then you pull the image from Docker Hub:

docker pull <image name>

Then you start a new container from the image:

docker run <image name> ...options

Here’s what it looks like for a Ghost blog I run:

docker stop ghost-blog
docker rm ghost-blog
docker pull ghost
docker run -d --name ghost-blog -p 2368:2368 \
  -v ghost-data:/var/lib/ghost/content ghost

Notice the last command repeats every option used in the original deploy: the name, the port mapping, the volume. Docker doesn’t remember them for you. If you forgot how the container was started, run docker inspect ghost-blog before removing it and copy the configuration from there.

Don’t lose your data

Be careful with docker rm: it deletes the container’s writable layer, so any data the application wrote inside the container’s own filesystem is gone.

That’s why the Ghost example mounts a volume with -v ghost-data:/var/lib/ghost/content. The content lives in the volume, which survives the removal, and the new container picks it up. If your container writes data you care about and has no volume, fix that first, then set up the update routine.

Automating it

Of course that’s not practical to do manually.

If you deploy with Docker Compose, updating gets shorter: docker compose pull followed by docker compose up -d pulls the new images and recreates only the containers whose image changed, reusing the options in the compose file.

Applications like Watchtower, deployed as a Docker container, lets you setup an automated workflow for watching changes on Docker Hub (or any other image registry) and automatically gracefully shut down an existing container and restart it with the same options that were used to deploy it initially.

Tagged: Docker · All topics
~~~

Related posts about docker: