Docker Run Command Basics

Master the docker run command with essential flags like -d, -it, --name, -p, -v, and -e. Learn how to start containers, map ports, mount volumes, and set environment variables.

Container Lifecycle

Detailed Explanation

Understanding docker run

The docker run command is the cornerstone of working with Docker. It creates a new container from an image and starts it in a single step.

Essential Flags

Detached mode (-d): Runs the container in the background, freeing your terminal.

docker run -d --name web nginx:alpine

Interactive mode (-it): Gives you an interactive shell inside the container.

docker run -it ubuntu:22.04 bash

Port mapping (-p): Maps a host port to a container port.

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

Volume mount (-v): Mounts a host directory or named volume into the container.

docker run -d -v ./data:/app/data my-app:latest

Environment variables (-e): Passes environment variables to the container.

docker run -d -e DATABASE_URL=postgres://... my-app:latest

Auto-Cleanup with --rm

For ephemeral containers (testing, debugging, one-off tasks), use --rm to automatically remove the container when it exits:

docker run --rm -it python:3.12 python -c "print('Hello')"

Naming Containers

Always name your containers with --name for easier management:

docker run -d --name postgres-dev -p 5432:5432 -e POSTGRES_PASSWORD=secret postgres:16

Without --name, Docker assigns a random name like quirky_mendel, making it harder to reference the container later.

Use Case

Starting application containers during development, running database services locally, executing one-off scripts in isolated environments, and prototyping with different runtime versions.

Try It — Docker CLI Reference

Open full tool