If you’re just starting to use Docker you’ve probably heard the terms Docker image and Docker container seemingly interchangeably. They are in fact 2 separate things. A Docker Image is an immutable (doesn’t change) snapshot of data containing binaries, libraries, code, etc. A Docker Container on the other hand is a runtime environment that runs your Docker image. To help clarify the Docker image vs container question we’ll go through a short overview (docker tutorial) of a common Docker workflow and point out some key differences along the way.
Docker Workflow: Docker image vs container
1.) Create a Dockerfile. A Dockerfile is more or less a list of instructions on how to build your Docker image. For example if we wanted to build an image that runs a containerized version of Ubuntu, installs vim (who doesn’t love vim?), and prints out “Hello” it would look like the code file below.
FROM ubuntu:20.04 RUN apt-get update && apt-get install -y vim CMD echo "Hello"
2.) Second, build a Docker image out of your Dockerfile instructions. Notice that I used the term Docker image rather than Docker container. When I run `docker build` it’s executing those Dockerfile instructions and creating an immutable snapshot AKA an image.
$ docker build . -f Dockerfile -t hello:latest Sending build context to Docker daemon 4.096kB Step 1/3 : FROM ubuntu:20.04 ---> f643c72bc252 Step 2/3 : RUN apt-get update && apt-get install -y vim ---> Using cache ---> daa377ad05ce Step 3/3 : CMD echo "Hello" ---> Using cache ---> 67a4f4514d62 Successfully built 67a4f4514d62 Successfully tagged hello:latest
3.) Let’s list our Docker images to make sure it’s there.
$ docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE hello latest 67a4f4514d62 2 minutes ago 167MB
4.) Run the Docker container using the Docker image. It should politely say “Hello” to you (how kind). A good distinction to make is that if you execute `docker run` you’re ‘running’ a container, if you execute `docker build` you’re ‘building’ an image.
$ docker run hello:latest Hello
5.) Even though our container ran and then shut down because it fulfilled it’s purpose we can list all of our containers whether they’re stopped or not with the `-a` flag on `docker container ls`.
$ docker container ls -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 60d1c1f1424d hello:latest "/bin/sh -c 'echo \"H…" About a minute ago Exited (0) About a minute ago wizardly_volhard
Thanks for reading! Hopefully this helped clarify the Docker Image vs Container differences for you. If you liked this hands on tutorial be sure to check out our articles on Docker Compose Environment Variables, our Docker Cheat Sheet, and the difference between Docker Entrypoint vs CMD.
If you live in AWS land and are having a difficult time understanding VPCs checkout our article on what is a vpc in aws.