Modern QA2026Running Containers — tiles
Log inJoin
43 / 55 · 19 Linux & Command Line · Docker Basics for QA← prev⊞ allnext →☰ Read as one page

6.3Running Containers

Basic Commands

# Run a container (pull image if not local, start, attach)
docker run -d --name test-db \
  -e POSTGRES_PASSWORD=testpass \
  -e POSTGRES_DB=test_db \
  -p 5432:5432 \
  postgres:16

# Flag breakdown:
# -d              Run in background (detached)
# --name test-db  Give it a meaningful name
# -e KEY=VALUE    Set environment variables
# -p 5432:5432    Map host port to container port (host:container)
# postgres:16     Image name and tag

Managing Containers

# List running containers
docker ps

# List all containers (including stopped)
docker ps -a

# Stop a container
docker stop test-db

# Start a stopped container
docker start test-db

# Restart a container
docker restart test-db

# Remove a stopped container
docker rm test-db

# Stop and remove in one step
docker stop test-db && docker rm test-db

# Remove all stopped containers
docker container prune

Viewing Logs

# View all container logs
docker logs test-db

# View last 50 lines
docker logs test-db --tail 50

# Follow logs in real-time (like tail -f)
docker logs test-db --follow

# Logs with timestamps
docker logs test-db --timestamps

# Combine: last 50 lines + follow
docker logs test-db --tail 50 --follow

Executing Commands in Containers

# Open an interactive shell in a running container
docker exec -it test-db bash

# Run a specific command
docker exec test-db psql -U postgres -d test_db -c "SELECT count(*) FROM users;"

# Run a command in a running container (non-interactive)
docker exec test-db pg_isready