How to run a Docker container

Topic: Containers core

Summary

Run a container with docker run: specify image, command, ports, volumes, and env. Use -d for detached, -p to publish ports, -v for volumes, -e for env vars. Use this when starting a single container or when testing an image before composing a stack.

Intent: How-to

Quick answer

  • docker run -d --name myapp -p 8080:80 -e KEY=value nginx:alpine. -d detached; --name name; -p host:container port; -e env var. Container keeps running if the main process does; exit when process exits unless --restart is set.
  • Volumes: -v /host/path:/container/path or -v volume_name:/container/path. Use named volumes for data that should persist; bind mount for config or source. Read-only: -v path:/container:ro.
  • Logs: docker logs myapp; docker logs -f myapp to follow. Stop: docker stop myapp; remove: docker rm myapp (or docker rm -f to force stop and remove). List: docker ps (running), docker ps -a (all).

Prerequisites

Steps

  1. Run with port and env

    docker run -d --name web -p 8080:80 -e NGINX_HOST=localhost nginx:alpine. Visit http://localhost:8080. -p 8080:80 maps host 8080 to container 80.

  2. Add volume

    docker run -d --name app -v mydata:/app/data myimage. Data in /app/data persists in volume mydata. Bind mount: -v $(pwd)/config:/app/config:ro for read-only config.

  3. Inspect and logs

    docker ps; docker logs app; docker logs -f app. docker inspect app for full config. docker exec -it app sh to get a shell inside the container.

  4. Stop and remove

    docker stop app; docker rm app. Or docker rm -f app to force. Remove image: docker rmi myimage. Prune unused: docker container prune; docker image prune.

Summary

Run containers with docker run; use -d, -p, -v, -e for detached, ports, volumes, and env. Use this to start and manage single containers.

Prerequisites

Steps

Step 1: Run with port and env

Use docker run with -d, —name, -p, and -e; verify the app is reachable.

Step 2: Add volume

Use -v for named volumes or bind mounts; use :ro for read-only when needed.

Step 3: Inspect and logs

Use docker ps, docker logs, and docker exec to inspect and debug.

Step 4: Stop and remove

Stop and remove containers; prune unused containers and images when appropriate.

Verification

  • Container runs and is reachable; logs are available; volume data persists after container removal.

Troubleshooting

Port already in use — Choose another host port or stop the conflicting container. Container exits immediately — Check logs (docker logs); ensure the main process does not exit (e.g. use a long-running command or entrypoint).

Next steps

Continue to