Docker Cheatsheet

This is not by any means a comprehensive list of commands, but are probably the one's I most commonly use when working with Docker.

Docker VM

List your installed docker machines
$ docker-machine ls
Create a new VM (primarily on Mac hosts) with storage greater than the default 20 GB (example, 100GB)
$ docker-machine -D create -d virtualbox --virtualbox-disk-size "100000" default

Images

Show all local images
$ docker images
Download an image from the repository
$ docker pull image-name
Delete an image
$ docker rmi image-name:tag
Build image from a local Dockerfile with a custom tag
$ docker build -t my-repo/my-image-name:tag .
View image tree structure (using dockviz)
$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nate/dockviz images -t

New Containers

Create a new container from an image, but don't start it
$ docker create image-name
Create a new container from an image and then start it
$ docker run image-name
Create a new container from an image and then start it with parameters
$ docker run -p PORT:PORT --name container-name -d image-name 

Existing Containers

Show running containers
$ docker ps
Show all containers
$ docker ps -a
Start up an existing container
$ docker start container-name
Restart an existing container
$ docker restart container-name
Stop an existing container
$ docker stop container-name
Delete an existing container
$ docker rm container-name
Save a copy of an existing container into a tar file
$ docker export --output="container-name.tar" container-name
Import a copy of an existing container (tar file) into a new container
$ docker import container-name.tar
Make a directory in an existing container
$ docker exec -i container-name sh -c 'mkdir -p /dest/to/you'
Copy a file into an existing container from a host
$ docker exec -i container-name sh -c 'cat > /dest/to/you/file.txt' < ./file.txt

Example

Installing a PostgreSQL container

This installs the latest Docker release of Postgres.

$ docker run -p 5432:5432 --name my-postgres-container -d postgres:latest
  • The run command means we want to create and start the container.
  • The -p 5432:5432 option defines port forwarding. It means forwarding docker container port 5432 to the docker host post 5432.
  • The --name option defines the new container name. In this case, it is my-postgres-container.
  • The -d option allows to run container as a daemon.
  • postgres is the name of the image
  • The :latest option can be any release id. See https://hub.docker.com/_/postgres/ for available versions.