---
title: "Docker Usage Guide"
publishedAt: "2024-08-25"
updatedAt: "2026-04-27"
summary:
  "Comprehensive guide to Docker commands for containerization, image
  management, and container orchestration with practical examples and best
  practices."
tags: [Docker, Containers, DevOps, CLI, Containerization]
language: "en"
type: "gist"
status: "published"
---

# Docker Usage Guide

This document collects practical Docker commands you can use in daily development and troubleshooting. It starts with the basics and then moves into more advanced but still broadly useful commands.

## Core Concepts

- **Image**: A read-only template used to create containers.
- **Container**: A running or stopped instance of an image.
- **Volume**: Persistent storage managed by Docker.
- **Network**: A virtual network used for container-to-container or host-to-container communication.

## Basic Commands

### Check Docker Version and Info

```bash
docker --version
docker version
docker info
```

- `docker --version` shows the installed CLI version.
- `docker version` shows both client and server versions.
- `docker info` shows engine details, storage driver, container count, and more.

### Search and Download Images

```bash
docker search nginx
docker pull nginx
docker pull node:20-alpine
```

- Use `search` to discover images on Docker Hub.
- Use `pull` to download a specific image and tag.

### List Local Images

```bash
docker images
docker image ls
```

### Run a Container

```bash
docker run nginx
docker run -d nginx
docker run -d -p 8080:80 --name web nginx
```

- `-d` runs the container in detached mode.
- `-p 8080:80` maps host port `8080` to container port `80`.
- `--name web` gives the container a readable name.

### List Running and All Containers

```bash
docker ps
docker ps -a
docker container ls
docker container ls -a
```

### Stop, Start, Restart, Remove

```bash
docker stop web
docker start web
docker restart web
docker rm web
docker rm -f web
```

- `rm -f` force removes a running container.

### Remove Images

```bash
docker rmi nginx
docker image rm nginx
```

## Interactive Usage

### Start a Shell in a New Container

```bash
docker run -it ubuntu bash
docker run -it alpine sh
```

- `-it` combines interactive and TTY modes.

### Open a Shell in an Existing Container

```bash
docker exec -it web sh
docker exec -it web bash
```

Use `exec` when the container is already running and you want to inspect or debug it.

## Logs and Monitoring

### View Container Logs

```bash
docker logs web
docker logs -f web
docker logs --tail 100 web
docker logs -f --tail 50 web
```

- `-f` follows live log output.
- `--tail` limits how many recent lines are shown.

### View Resource Usage

```bash
docker stats
docker stats web
```

This is useful for checking CPU, memory, network, and block I/O usage.

## Inspecting Containers and Images

### Detailed Inspection

```bash
docker inspect web
docker inspect nginx
```

This returns JSON with configuration, mounts, ports, IP address, and metadata.

### Useful Inspect Filters

```bash
docker inspect -f '{{.NetworkSettings.IPAddress}}' web
docker inspect -f '{{json .Mounts}}' web
docker inspect -f '{{.State.Status}}' web
```

These filtered templates are much faster than reading the full JSON output.

### View Port Mappings

```bash
docker port web
```

## Working with Files

### Copy Files Between Host and Container

```bash
docker cp ./local.txt web:/tmp/local.txt
docker cp web:/var/log/nginx/access.log ./access.log
```

### Mount a Host Directory

```bash
docker run -d -p 8080:80 -v $(pwd):/app node:20-alpine
```

This mounts the current host directory into `/app` inside the container.

## Volumes

### Create and List Volumes

```bash
docker volume create app_data
docker volume ls
```

### Use a Volume

```bash
docker run -d --name db -v app_data:/var/lib/mysql mysql:8
```

### Inspect and Remove Volumes

```bash
docker volume inspect app_data
docker volume rm app_data
```

Volumes are preferred over container-local storage when data must survive container recreation.

## Networks

### List and Create Networks

```bash
docker network ls
docker network create app_net
```

### Attach a Container to a Network

```bash
docker run -d --name api --network app_net nginx
docker network connect app_net web
```

### Inspect and Remove Networks

```bash
docker network inspect app_net
docker network rm app_net
```

Custom networks are useful when multiple containers need to communicate by container name.

## Building Images

### Build from a Dockerfile

```bash
docker build -t my-app .
docker build -t my-app:1.0 .
docker build -f Dockerfile.dev -t my-app:dev .
```

### Tag and Push Images

```bash
docker tag my-app:1.0 username/my-app:1.0
docker push username/my-app:1.0
```

## Advanced but Useful Commands

### Show Only Specific Fields with `--format`

```bash
docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}'
```

This is very useful when you want readable CLI output without manual filtering.

### Filter Results

```bash
docker ps -a --filter "name=web"
docker images --filter "dangling=true"
docker volume ls --filter "name=app"
```

### Inspect Container Processes

```bash
docker top web
```

This helps when debugging containers that appear healthy but are not doing the expected work.

### See Container Changes

```bash
docker diff web
```

This shows filesystem changes inside a container since it was created.

### Commit a Container as an Image

```bash
docker commit web debug/web:snapshot
```

This is helpful for temporary debugging workflows, though rebuilding from a Dockerfile is usually better for long-term use.

### Save and Load Images

```bash
docker save -o my-app.tar my-app:1.0
docker load -i my-app.tar
```

Useful when moving images between environments without pulling from a registry.

### Export and Import Container Filesystems

```bash
docker export web -o web.tar
docker import web.tar imported-web:latest
```

Unlike `save` and `load`, this works with container filesystems instead of image layers.

### Run Commands in One-Off Containers

```bash
docker run --rm alpine ls -la
docker run --rm node:20-alpine node -v
```

- `--rm` removes the container automatically after the command finishes.

### Set Environment Variables

```bash
docker run -e NODE_ENV=production my-app
docker run --env-file .env my-app
```

### Run PostgreSQL with Environment Configuration

```bash
docker run -d \
  --name postgres-db \
  -e POSTGRES_DB=myapp \
  -e POSTGRES_USER=myuser \
  -e POSTGRES_PASSWORD=mypassword \
  -p 5432:5432 \
  -v postgres_data:/var/lib/postgresql/data \
  postgres:16
```

This starts PostgreSQL with a database, user, password, port mapping, and a persistent volume.

Example using an environment file:

```bash
docker run -d \
  --name postgres-db \
  --env-file .env.postgres \
  -p 5432:5432 \
  -v postgres_data:/var/lib/postgresql/data \
  postgres:16
```

Example `.env.postgres` content:

```env
POSTGRES_DB=myapp
POSTGRES_USER=myuser
POSTGRES_PASSWORD=mypassword
```

Useful PostgreSQL follow-up commands:

```bash
docker logs -f postgres-db
docker exec -it postgres-db psql -U myuser -d myapp
docker exec -it postgres-db sh
```

If you want a temporary PostgreSQL container with no persisted data, remove the volume mount:

```bash
docker run -d \
  --name postgres-temp \
  -e POSTGRES_DB=myapp \
  -e POSTGRES_USER=myuser \
  -e POSTGRES_PASSWORD=mypassword \
  -p 5432:5432 \
  postgres:16
```

### Limit CPU and Memory

```bash
docker run -d --memory="512m" --cpus="1.5" my-app
```

This is useful for testing behavior under constrained resources.

### Restart Policies

```bash
docker run -d --restart unless-stopped nginx
docker run -d --restart always nginx
```

This is practical for local servers and lightweight long-running services.

### Health Checks

```bash
docker run -d \
  --health-cmd="curl -f http://localhost || exit 1" \
  --health-interval=30s \
  --health-timeout=5s \
  --health-retries=3 \
  nginx
```

Health checks help detect containers that are running but not actually ready.

## Cleanup Commands

### Remove Stopped Containers

```bash
docker container prune
```

### Remove Unused Images

```bash
docker image prune
docker image prune -a
```

### Remove Unused Volumes

```bash
docker volume prune
```

### Remove Unused Networks

```bash
docker network prune
```

### Clean Everything Unused

```bash
docker system prune
docker system prune -a --volumes
```

Be careful with prune commands because they can remove data you still need.

### Remove All Containers Shown by `docker ps -a`

```bash
docker rm -f $(docker ps -aq)
```

This force-removes every container, including running ones.

### Remove All Containers and Related Artifacts

If you want to remove all containers and also delete unused images, volumes, networks, and build cache:

```bash
docker rm -f $(docker ps -aq)
docker system prune -a --volumes -f
```

If you want a more explicit cleanup flow:

```bash
docker rm -f $(docker ps -aq)
docker volume rm $(docker volume ls -q)
docker network prune -f
docker image prune -a -f
docker builder prune -a -f
```

Use the explicit version carefully. Removing all volumes deletes persisted database and application data.

### Safer Variant for Scripts

If there may be no containers or no volumes, this avoids command errors:

```bash
docker ps -aq | xargs -r docker rm -f
docker volume ls -q | xargs -r docker volume rm
docker system prune -a --volumes -f
```

## Docker Compose Essentials

If Docker Compose is available through the Docker CLI plugin:

```bash
docker compose up
docker compose up -d
docker compose down
docker compose ps
docker compose logs -f
docker compose exec app sh
docker compose build
```

These are the most commonly used commands for multi-container applications.

### Docker Watch

For most development workflows, Docker Watch is used through `docker compose watch`.

```bash
docker compose watch
docker compose watch app
docker compose watch --no-up
docker compose watch --dry-run
```

- `docker compose watch` watches the configured services for file changes.
- `docker compose watch app` watches only the `app` service.
- `--no-up` skips the initial build and startup step.
- `--dry-run` shows what would happen without applying changes.

Docker Watch is especially useful in development because it can sync changed files into the container or trigger a rebuild automatically.

Example `compose.yml` configuration:

```yaml
services:
  app:
    build: .
    ports:
      - "3000:3000"
    command: npm run dev
    develop:
      watch:
        - action: sync
          path: .
          target: /app
          ignore:
            - node_modules/
        - action: rebuild
          path: package.json
```

What this example does:

- Changes in the project folder are synced into `/app` in the container.
- Changes to `package.json` trigger an image rebuild.
- `node_modules/` is ignored to avoid unnecessary sync noise.

Typical workflow:

```bash
docker compose up -d
docker compose watch
```

This is a good alternative to bind mounts when you want more controlled file sync behavior.

## Practical Troubleshooting Examples

### Check Why a Container Exits Immediately

```bash
docker ps -a
docker logs <container_name>
docker inspect -f '{{.State.ExitCode}}' <container_name>
```

### Check Network Reachability Between Containers

```bash
docker exec -it api sh
ping web
```

### Check Mounted Files

```bash
docker inspect -f '{{json .Mounts}}' web
```

### Check Real Startup Command

```bash
docker inspect -f '{{.Config.Cmd}}' web
docker inspect -f '{{.Config.Entrypoint}}' web
```

## Recommended Daily Commands

If you only remember a short set, these are the most useful in daily work:

```bash
docker ps -a
docker logs -f <container>
docker exec -it <container> sh
docker inspect <container>
docker build -t my-app .
docker run -d -p 8080:80 --name my-app my-app
docker compose up -d
docker system prune
```

## Notes

- Prefer named containers for easier management.
- Prefer volumes for persistent data.
- Prefer `--rm` for short-lived utility containers.
- Use `inspect`, `logs`, and `exec` first when debugging.
- Use prune commands carefully in environments with important local data.
