Even if you only want to create docker images for purpose of running them in a Kubernetes cluster, you'll still likely want to run them locally from time to time, if only to test them. For this, use docker run.

docker run starts a container corresponding to the image you give it. For example,

docker run busybox:1.31.1

will create a new container based on the busybox:1.31.1 image and run it.

Here are some useful arguments to use with docker run:

  • -d runs the container in the background. Example: docker run -d nginx:1.17.8
  • --rm removes the container after it finishes running. This can be useful to prevent you from building a huge backlog of stopped containers (see "docker stop" below). Example: docker run --rm busybox:1.31.1
  • -p creates a port mapping between the docker container and the host. This is very important for any web server or microservice that listens for incoming traffic on a port. Example: docker run -p 80:80 nginx:1.17.8 Note: when you see port mappings that have two ports on either side of a colon, the first port is the one on the host, and the second on the container.
  • --name assigns a name to the resulting container that is used by the Docker backend for tracking it. Otherwise it will assign its own name that may be difficult for you to remember. Example: docker run --name my-redis redis:7.2.5

See some of these in action by running the following:

docker run -d -p 8080:80 nginx:1.17.8

and then, in your browser, go to http://localhost:8080. You'll connect to the nginx service running inside the container. This is the same way you'd connect to a microservice you built in your own containers.

docker tag

docker tag adds a tag to an existing image. For example: docker tag my-image my-image:0.0.1

docker ps

docker ps shows a list of running containers and some info about them.

Use the -a argument (docker ps -a) to show both running containers and stopped containers.

docker stop

docker stop <container-name> stops a container. (Get the container name from docker ps, or use the name you'd given it from using the --name argument). Note that the container's process is stopped, but the container's metadata remains, and containers stopped in this way can be started again through docker start.

docker rm

docker rm <container-name> removes the metadata of a stopped container.

docker start

docker start <container-name> starts a container that had previously been stopped with docker stop.

docker logs

docker logs <container-name> displays the logs the container's interior process had written to stdout and stderr. Note that, as a general rule, processes in containers should write their logs to stdout and stderr, and not to a log file.