Docker & Docker-Compose Cheat Sheet for DevOps Beginners

Docker & Docker-Compose Cheat Sheet for DevOps Beginners

#90DaysofDevOps Challenge - Day 20

▶Docker

It provides the ability to package and run an application in a loosely isolated environment called a container.

The isolation and security allow you to run many containers simultaneously on a given host.

The Containers are lightweight and contain everything needed to run the application, so you do not need to rely on what is currently installed on the host.

You can easily share containers while you work, and be sure that everyone you share with gets the same container that works in the same way.

Installation

Docker Desktop is available for Mac, Linux and Windows: https://docs.docker.com/desktop

Check out our docs for information on using Docker: https://docs.docker.com

▶General Docker Commands with a brief explanation for the use of each one.

Running a new container

Start a new Container from an Image:

$ docker run <image_name>
$ docker run nginx

Assing it a name

$ docker run --name <container_name>
$ docker run --name web nginx

Map a specific port

$ docker run -p <hostport>:<containerport> <image_name>
$ docker run -p 8080:80 nginx

Map all ports

$ docker run -p <image_name>
$ docker run -p nginx

Start the container in the background

$ docker run -d <image_name>
$ docker run -d nginx

Assign it a hostname

$ docker run --hostname <hostname> <image_name>
$ docker run --hostname srv nginx

Add a DNS entry

$ docker run --add-host <hostname>:IP <image_name>

Map a local directory into the container

$ docker run -v <hostdir>:/<targetdir> <image_name>
$ docker run -v ~/:/usr/share/nginx/html nginx

Change the Entrypoint

$ docker run -it --entrypoint executable <image_name>
$ docker run -it entrypoint bash nginx

Manage Container

List of running containers

$ docker ps

List of all containers

$ docker ps -a

Delete a container

$ docker rm <container>
$ docker rm test

Delete a running container (Note - You can try to kill the service first and then try to remove it after that).

$ docker rm -f <container> 
$ docker rm -f nginx
OR
$ docker kill <container> 
$ docker kill test
$ docker rm -f <container> 
$ docker rm -f test

Stop a running service

$ docker stop <container>
$ docker stop test

Start a stopped container

$ docker start <container>
$ docker start test

Copy a file from a container to the host

$ docker cp <container>:<source> <target>
$ docker cp nginx:/index.html index.html

Copy a file from the host to a container

$ docker cp <target> <container>: <source>
$ docker cp test:/index.html index.html

Start a Shell inside a running container

$ docker exec -it <container> executable
$ docker exec -it test bash

Rename a container

$ docker rename <old_name_container> <new_name_container>
$ docker rename test nginx

Create an image out of the container

$ docker commit <container>
$ docker commit test

Manage Images

Download an image

$ docker pull <image_name>:<tag>
$ docker pull nginx:latest

Upload an image to a repository

$ docker push <image_name>
$ docker push testimage:v1

Delete an image

$ docker rmi <image_name>
$ docker rmi nginx

Delete dangling images

$ docker image prune
$ docker rmi nginx

Delete all unused images

$ docker image prune -a

Show a list of all images

$ docker images

Build an image from a Dockerfile

$ docker build <dir>
$ docker build .

Tag an image

$ docker tag <image_name> <newimage_name>
$ docker tag nginx nginx:latest

Build and tag an image from a Dockerfile

$ docker build -t <image_name> <dir>
$ docker build -t testimage .

Save an image to .tar file

$ docker save <image_name> > <file>.tar
$ docker save nginx > nginx.tar

Load an image from a .tar file

$ docker load -i <tar_file>
$ docker load -i nginx.tar

For Information and Stats

Show the logs of a container

$ docker logs <container_name>
$ docker logs test

Show stats of running containers

$ docker stats

Show processes of container

$ docker top <container_name>
$ docker top test

Show installed docker version

$ docker version

Get detailed info about an object

$ docker inspect <object_name>
$ docker inspect nginx

Show all modified files in a container

$ docker diff <container_name>
$ docker diff test

Show mapped ports of a container

$ docker port <container_name>
$ docker port test

▶General Docker-Compose Commands with a brief explanation for the use of each one.

File Structure

docker-compose.yml (Example)

#docker-compose.yml file
version: '3'
services:
  # Your web application => Container
  web:
    build: .
    ports:
    - "5000:5000"

  # Redis cache container
  redis:
    image: "redis:alpine"

To Start a Project

It tries to automate a series of operations including building a mirror, (re)creating a service, starting a service, and associating a service-related container. Sometimes you will need docker-compose up --rebuild after making code changes.

$ docker-compose up [options] [--scale SERVICE=NUM...] [SERVICE...]

Some other options to use:

-d, --detach – Run containers in the background

--no-color – Produce monochrome output.

--no-deps – Don’t start linked services.

--force-recreate – Recreate containers even if their configuration and image haven’t changed.

--always-recreate-deps – Recreate dependent containers.

--no-recreate – If containers already exist, don’t recreate
them.

--no-build – Don’t build an image, even if it’s missing.

--no-start – Don’t start the services after creating them.

--build – Build images before starting containers.

-t, --timeout – TIMEOUT Use this timeout in seconds for container shutdown when attached or when containers are already running. (default: 10)

--remove-orphans – Remove containers for services not defined in the Compose file.

To build (rebuild) the service

$ docker-compose build [options] [SERVICE...]

Some other options to use:

--compress – Compress the build context using gzip.

--force-rm – Always remove intermediate containers.

--no-cache – Do not use cache when building the image.

--pull – Always attempt to pull a newer version of the image.

-m, --memory – MEM Sets memory limit for the build container.

--build-arg key=val – Set build-time variables for services.

--parallel – Build images in parallel.

Stops containers

It removes containers, networks, volumes, and images (defined in docker-compose.yml) created by up

$ docker-compose down [options]

Some other options to use:

--rmi type – Remove images. Type is ‘all’ or ‘local’

-v, --volumes – Remove named volumes declared in the volumes section of the Compose file and anonymous volumes attached to containers.

--remove-orphans – Remove containers for services not defined in the Compose file

-t, --timeout – TIMEOUT Specify a shutdown timeout in seconds. default – 10.

To start an existing service container

$ docker-compose start [SERVICE...]

To stop running containers without removing them.

They can be started again with docker-compose start.

$ docker-compose up [options] [--scale SERVICE=NUM...] [SERVICE...]

Some other options to use:

-d, --detach – Run containers in the background

--no-color – Produce monochrome output.

--no-deps – Don’t start linked services.

--force-recreate – Recreate containers even if their configuration and image haven’t changed.

--always-recreate-deps – Recreate dependent containers.

--no-recreate – If containers already exist, don’t recreate
them.

--no-build – Don’t build an image, even if it’s missing.

--no-start – Don’t start the services after creating them.

--build – Build images before starting containers.

-t, --timeout – TIMEOUT Use this timeout in seconds for container shutdown when attached or when containers are already running. (default: 10)

--remove-orphans – Remove containers for services not defined in the Compose file.

To show a list of containers for a service

$ docker-compose ps [options] [SERVICE...]

Some other options to use:

-q, --quiet – Only display IDs

--services – Display services

--filter – KEY=VAL Filter services by a property

-a, --all – Show all stopped containers (including those created by the run command)

Generates a Distributed Application Bundle (DAB) from the Compose file

$ docker-compose bundle [options]

Some other options to use:

--push-images – Automatically push images for any services which have a build option specified.

-o, --output – PATH Path to write the bundle file to. Defaults to “.dab”.

To pause running containers of a service

They can be unpaused with docker-compose unpause

$ docker-compose pause [SERVICE...]

To unpause paused containers of a service

$ docker-compose unpause [SERVICE...]

To verify that the Compose file format is correct

$ docker-compose config [options]

Some other options to use:

--resolve-image-digests – Pin image tags to digests.

-q, --quiet – Only validate the configuration, don’t print anything.

--services – Print the service names, one per line.

--volumes – Print the volume names, one per line.

--hash="*" – Print the service config hash, one per line. Set “service1,service2” for a list of specified services or use the wildcard symbol to display all services.

To allocate a TTY

Example, use docker-compose exec web sh to get an interactive prompt.

$ docker-compose exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]

Some other options to use:

-d, --detach – Detached mode: Run command in the background.

--privileged – Give extended privileges to the process.

-u, --user – USER Run the command as this user.

-T – Disable pseudo-tty allocation. By default docker-compose exec allocates a TTY.

--index=index – index of the container if there are multiple instances of service [default: 1]

-e, --env – KEY=VAL Set environment variables (can be used multiple times, not supported in API < 1.25)

-w, --workdir – DIR Path to workdir directory for this command.

To stream container events for every container in the project

Example docker-compose events --json to stream in JSON format.

$ docker-compose events [options] [SERVICE...]

Some other options to use:

--json – Output events as a stream of JSON objects

To display help and usage instructions for a command

$ docker-compose help COMMAND

To display log output from services

$ docker-compose logs [options] [SERVICE...]

Some other options to use:

--no-color – Produce monochrome output.

-f, --follow – Follow log output.

-t, --timestamps – Show timestamps.

--tail="all" – Number of lines to show from the end of the logs for each container.

To force running containers to stop by sending a SIGKILL signal

Optionally the signal can be passed, for example: docker-compose kill -s SIGINT

$ docker-compose kill [options] [SERVICE...]

Some other options to use:

-s SIGNAL – SIGNAL to send to the container. The default signal is SIGKILL

To print the public port to which a container port is mapped

$ docker-compose port [options] SERVICE PRIVATE_PORT

Some other options to use:

--protocol=proto – tcp or udp [default: tcp]

--index=index – index of the container if there are multiple instances of a service [default: 1]

To restart all stopped and running services

$ docker-compose restart [options] [SERVICE...]

Some other options to use:

-t, --timeout – TIMEOUT Specify a shutdown timeout in seconds. (default: 10)

To pull an image associated with a service defined in a docker-compose.yml

$ docker-compose pull [options] [SERVICE...]

Some other options to use:

--ignore-pull-failures – Pull what it can and ignores images with pull failures.

--parallel – Deprecated, pull multiple images in parallel (enabled by default).

--no-parallel – Disable parallel pulling.

-q, --quiet – Pull without printing progress information

--include-deps – Also pull services declared as dependencies

To remove stopped service containers

$ docker-compose rm [options] [SERVICE...]

Some other options to use:

-f, --force – Don’t ask to confirm the removal

-s, --stop – Stop the containers, if required, before removing

-v – Remove any anonymous volumes attached to containers

To push images for services to their respective registry/repository

$ docker-compose push [options] [SERVICE...]

Some other options to use:

--ignore-push-failures – Push what it can and ignores images with push failures.

To view the processes running within each service container

$ docker-compose top [SERVICE...]

To print the version of docker-compose

$ docker-compose version

To run a one-time command against a service

For example, the following command starts the web service and runs bash as its command docker-compose run web bash.

$ docker-compose run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] SERVICE [COMMAND] [ARGS...]

Some other options to use:

-d, --detach – Detached mode: Run container in the background, print new container name.

--name NAME – Assign a name to the container

--entrypoint CMD – Override the entrypoint of the image.

-e KEY=VAL – Set an environment variable (can be used multiple times)

-l, --label KEY=VAL – Add or override a label (can be used multiple times)

-u, --user="" – Run as specified username or uid

--no-deps – Don’t start linked services.

--rm – Remove container after run. Ignored in detached mode.

-p, --publish=[] – Publish a container’s port(s) to the host

--service-ports – Run command with the service’s ports enabled and mapped to the host.

--use-aliases – Use the service’s network aliases in the network(s) the container connects to.

-v, --volume=[] – Bind mount a volume (default [])

-T – Disable pseudo-tty allocation. By default docker-compose run allocates a TTY.

-w, --workdir="" – Working directory inside the container

Forgive me for the extensive read since I tried to be more detailed as possible.

It was a nutshell of Docker and Docker Compose commands, and I hope it is helpful to you.