Skip to main content
⚡ OpenDevDocs
Docker
devopsdockerGuideBeginner

Docker Run & Container Execution

Complete guide to running containers with docker run, including interactive modes, detached background mode, auto-removal, restart policies, and environment configuration.

Verified: 2026-09-30
Tested on:docker 27.x
Platforms:
linuxmacoswindows
#docker#run#containers#devops

The docker run command creates a new container layer over a specified image and starts it.


Basic Syntax

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Essential Flags

FlagDescriptionExample
-d, --detachRuns container in the background (detached mode)docker run -d nginx
-i, --interactiveKeeps STDIN open even if not attacheddocker run -it alpine sh
-t, --ttyAllocates a pseudo-TTY terminaldocker run -it ubuntu bash
--nameAssigns a custom name to the containerdocker run --name my-redis -d redis
-p, --publishMaps host port to container port (HOST:CONTAINER)docker run -p 8080:80 nginx
-v, --volumeMounts a volume or bind mountdocker run -v ./data:/data redis
-e, --envSets environment variablesdocker run -e NODE_ENV=production app
--rmAutomatically removes container when it exitsdocker run --rm alpine ls -la
--restartSets container restart policydocker run --restart unless-stopped app

Common Examples

1. Interactive Ephemeral Shell

docker run --rm -it alpine:latest sh

2. Detached Web Server with Port Forwarding

docker run -d --name web-server -p 80:80 nginx:alpine

3. Database with Persistent Volume and Env Vars

docker run -d \
  --name local-postgres \
  -e POSTGRES_PASSWORD=secret \
  -e POSTGRES_USER=postgres \
  -v pgdata:/var/lib/postgresql/data \
  -p 5432:5432 \
  postgres:16-alpine

Restart Policies

PolicyBehavior
noDo not automatically restart container (Default).
on-failure[:max-retries]Restart only if container exits with non-zero exit code.
alwaysAlways restart regardless of exit status. Restarts on daemon reboot.
unless-stoppedAlways restart unless manually stopped by docker stop.

On this page