Launching Containers
# Basic syntax
docker run [OPTIONS] IMAGE [COMMAND]
# Lifecycle on first run
# 1. Local image lookup → download if missing
# 2. Container creation → default or supplied command
# 3. Container ID returned
docker run -d nginx
Frequently-used run flags
| Short / Long |
Purpose |
-d |
Detached / daemon mode |
-p host:ctr |
Publish specific port |
-P |
Publish random high port |
-i |
Keep stdin open |
-t |
Allocate pseudo-TTY |
-v host:ctr[:ro] |
Bind mount volume |
--rm |
Auto-remove on exit |
--name |
Assign custom name |
--network |
Attach to chosen network |
-e KEY=VAL |
Inject environment variable |
--link |
Legacy container linking |
-h hostname |
Override cnotainer hostname |
--privileged |
Extended host privileges |
Flag examples
# Detached nginx
docker run -d nginx
# Fixed port mapping
docker run -d -p 8080:80 nginx
# Random port mapping
docker run -d -P nginx
# Interactive shell
docker run -it centos:7 bash
# Host volume mount
docker run -it -v /opt:/root centos:7 bash
# Ephemeral container
docker run -d --rm nginx
# Named container
docker run -d --name web nginx
# Custom network
docker network create demo
docker run -d --net demo nginx
# Environment variable
docker run -it -e GREET=hello centos:7 bash
# Legacy link (still useful for quick tests)
docker run -d --name db postgres:13
docker run -it --link db:pg centos:7 bash
# Custom hostname
docker run -it -h mybox centos:7 bash
# Full privileges
docker run -it --privileged ubuntu bash
Listing Containers
# Active containers
docker ps
# All containers (running & exited)
docker ps -a
# IDs only
docker ps -q
docker ps -aq
Start / Stop Lifecylce
# Stop
docker stop web
# Start
docker start web
Removing Containers
# Single container
docker rm web
# Force removal
docker rm -f web
# Bulk cleanup
docker rm -f $(docker ps -aq)
Inspecting Containers
# Full JSON
docker inspect web
# Extract running state
docker inspect -f '{{.State.Running}}' web
File Transfer
# Host → container
docker cp ./data.csv web:/tmp
# Container → host
docker cp web:/var/log/nginx/access.log ./
Accessing a Running Container
1. Preferred: exec
docker exec -it web bash
2. Legacy: attach
docker attach web # shares the main PID; exit kills container
3. Low-level: nsenter
PID=$(docker inspect -f '{{.State.Pid}}' web)
nsenter --target $PID --mount --uts --ipc --net --pid
4. SSH (when container runs sshd)
ssh root@$(docker inspect -f '{{.NetworkSettings.IPAddress}}' web)