Mastering Docker Commands: A 26-Step Guide for Developers and Sysadmins

As companies continue their rapid migration to cloud-native and microservices-based architectures, Docker has become an indispensable tool for streamlining development and simplifying deployment.

According to Datadog’s 2022 Container Report, adoption growth remains high, with 97% of organizations now running containers in production – a 3X increase since 2016. Much of this growth is fueled by Docker‘s impact on developer productivity and operations efficiency.

So whether you‘re looking to containerize legacy apps or build new cloud-native microservices – mastering basic Docker commands is a must.

In this comprehensive reference guide, we will break down 26 essential Docker commands that every developer and sysadmin should know.

Docker Overview

Before we jump into the commands, let‘s quickly recap what Docker actually is and why it‘s useful:

Docker is an open platform for developing, shipping, and running applications within containers – self-sufficient packages with all dependencies bundled in. Unlike VMs which simulate hardware, containers provide OS-level virtualization by abstracting the Linux kernel.

This makes containers extremely lightweight, fast, and portable across environments. Some key advantages over VMs include:

  • Faster startup times – containers skip the bootup phase
  • Better resource efficiency – containers share the host OS kernel
  • Consistency across environments – identical images run the same everywhere
  • Microservices friendly – complex systems as modular containers
  • Simpler dependency handling – bundles all libraries, systems tools etc
  • Improved CI/CD – create/deploy containers at scale

With Docker, you can package an app or service along with all its dependencies into a standardized unit for software development. This container image defines the app environment and can be easily shared and deployed across machines – from a developer laptop to a production server running thousands of containers.

Now let‘s explore how to leverage Docker for app development and deployment using key command line operations.

Getting Started: Docker Setup

Before running Docker commands, first ensure Docker Engine is installed on your preferred OS:

Mac | Windows | Linux

Once Docker is running, verify the install via docker --version:

docker --version

# Output
Docker version 20.10.12, build 20.10.12-0ubuntu4~20.04.2

Great – you now have access to all Docker client commands. Let‘s explore them categorized by function.

Docker Container Lifecycle Commands

Containers are runtime instances of Docker images. Let‘s go over key commands for managing container lifecycles.

docker run

The docker run command starts a new Docker container from a given image:

docker run -d --name my-nginx -p 80:80 nginx

This runs an Nginx Docker container named my-nginx in detached mode -d, forwards host port 80 to container port 80, and pulls the nginx image if missing locally.

Some common docker run options:

-d # Run container in background 
--name # Name the running container  
-p # Forward host ports to container ports
--rm # Delete container on exit
-it # Interactive shell 
--cpus # Set CPU limits
--memory # Set RAM limits

docker start/stop

Start or stop an existing Docker container:

docker start my-container
docker stop my-container 

docker ps

List all running Docker containers:

docker ps

# Sample Output
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                                       NAMES
dbcdbab85cf9   nginx:latest   "/docker-entrypoint...."   10 minutes ago   Up 10 minutes   0.0.0.0:80->80/tcp, :::80->80/tcp           my-nginx

Add -a flag to include stopped containers too.

docker exec

Execute a command inside a running Docker container:

# Run bash session inside container 
docker exec -it my-nginx bash  
# Create file
docker exec my-container touch /tmp/testfile  

docker logs

Fetch stdout/stderr logs from a running container using container ID or name:

docker logs -f my-nginx

docker stop/rm

Stop and remove a container (use -f to force):

docker stop my-container
docker rm my-container

This covers basic container management! Now let‘s look at core image commands.

Essential Docker Image Commands

Docker containers are instantiated from read-only images that bundle code and dependencies. Here are key image commands:

docker images

List downloaded Docker images present locally:

docker images

# Sample Output
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         latest    06a618e13477   3 days ago     133MB
ubuntu        18.04     775349758637   2 weeks ago    63.1MB

docker pull

Download ("pull") an image from a registry like Docker Hub:

docker pull nginx:1.19-alpine

docker rmi

Delete an image from local storage:

docker rmi nginx:1.19-alpine 

docker build

Build an image from a Dockerfile present locally in the build context:

# Dockerfile

FROM python:3.8-slim  

COPY . /app  
RUN pip install -r requirements.txt

CMD ["python", "app.py"]  
docker build -t my-python-app:v1 . 

This builds a Docker image named my-python-app with tag v1 using current directory (.) as build context.

docker history

View layers associated with an image – useful for diagnosing size issues:

docker history nginx:latest

docker inspect

Return detailed metadata and settings for a given image:

docker inspect ubuntu:latest

Now that you know essential image commands, let‘s look at networking options.

Docker Network Commands

By default, Docker containers run on a private virtual bridge network automatically created by the Engine:

docker-default-network.png

But containers can also be attached to additional networks. Here are some key Docker networking commands:

docker network create

Create a new Docker network:

# Create overlay network  
docker network create --driver overlay my-multi-host-network

# Create bridge network
docker network create my-bridge-network

docker network ls

List available networks:

docker network ls

NETWORK ID     NAME                         DRIVER    SCOPE
18a2866682b8   bridge                       bridge    local
488db710a6bf   my-bridge-network            bridge    local
63c0f80938cf   my-multi-host-overlay        overlay   swarm 

docker network inspect

Inspect a network‘s driver, IPAM settings, connected containers etc:

docker network inspect my-multi-host-overlay

docker network connect

Attach a container to a network:

docker network connect my-multi-host-overlay my-container

This enables connectivity between multiple containers across different Docker daemons.

Now let‘s go over some quick volume commands.

Handling Persistent Storage with Docker Volumes

Docker containers are ephemeral by default – all data is lost when a container is removed. Volumes provide persistent data storage outside the container UFS filesystem:

docker volumes.png

This keeps data intact across container restarts and allows sharing between containers. Here are some basic volume operations:

docker volume create

docker volume create my-volume

docker volume ls

List volumes:

docker volume ls

DRIVER    VOLUME NAME
local     my-volume

docker volume inspect

Inspect volume metadata/properties:

docker volume inspect my-data

docker volume rm

Remove a volume:

docker volume rm my-volume 

This covers Docker volume basics – let‘s finish off with some extra useful commands.

Other Helpful Docker Commands

Here are some other common Docker operations:

docker login

Log in to a Docker registry using credentials:

docker login
# Follow prompts for username, password etc

docker search

Search Docker Hub for images:

docker search nginx

NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
nginx                             Official build of Nginx.                        15005     [OK]       
jwilder/nginx-proxy               Automated Nginx reverse proxy for docker con...   2115                 [OK]

docker stats

View live resource usage statistics for running containers:

docker stats

CONTAINER ID   NAME          CPU %     MEM USAGE / LIMIT     MEM %     NET I/O       BLOCK I/O     PIDS
c871e4b28a3c   my-app       1.39%     44.4MiB / 1.934GiB   2.24%     1.422kB / 0B   16.81MB / 0B   8

docker system

Manage Docker disk usage:

# Clean unused data  
docker system prune

docker commit

Create a new image from changes made to a container:

docker commit my-nginx my-custom-nginx

This just scratches the surface of what‘s possible with Docker! For production environments, be sure to follow Docker security best practices.

Conclusion

Having a solid grasp of common docker commands empowers developers and sysadmins to fully leverage containers. You can now:

  • Package and distribute applications as portable images
  • Launch containers locally or on cloud VMs
  • Manage container networking, storage, and resources
  • Streamline your CI/CD pipeline with standardized artifacts

This was just a subset of popular Docker capabilities – but mastering these 26 fundamental commands lays the groundwork for running containerized apps at scale.

For more comprehensive coverage, check out KodeKloud‘s in-depth Docker course or the official Docker CLI reference docs.

Hope this guide helps you become a Docker power user! Let me know in the comments if you have any other Docker questions.