Skip to main content

Docker Fundamentals

Docker is a platform that allows you to package applications and their dependencies into lightweight, portable containers. Under the hood, Docker uses Linux namespaces (to isolate processes, networking, and filesystems) and cgroups (to manage resource limits such as CPU and memory). This combination provides the foundation of containerization: process isolation without the overhead of a full virtual machine.



Pulling Images

Images are templates used to create containers. To fetch an image from Docker Hub:

# Pull the lightweight Alpine Linux image
docker image pull alpine

# Pull the Nginx web server image
docker image pull nginx

Running Containers

Create and start a container from an image:

# Run a shell inside an Alpine container
docker run -it alpine sh
  • -i keeps STDIN open.
  • -t allocates a pseudo-TTY.

You can list running containers:

docker ps

List all containers (including stopped ones):

docker ps -a

Attaching & Detaching

Detach from a running container without stopping it:

<C-p><C-q>

Reattach later:

docker attach <container_id_or_name>

Logs

View logs from a container:

docker logs <container_id_or_name>

Follow logs in real time:

docker logs -f <container_id_or_name>

Lifecycle Commands

  • Stop:

    docker stop <container>
  • Start:

    docker start <container>
  • Pause / Resume:

    docker pause <container>
    docker unpause <container>
  • Rename:

    docker rename old_name new_name

Environment & Limits

Set environment variables at container creation:

docker run -e MYVAR=value alpine env

View environment variables inside a running container:

docker exec <container> env

Set ulimits for resource control:

docker run --ulimit nofile=1024:2048 alpine

Inspecting Containers

Inspect low-level details:

docker inspect <container>

This returns JSON with network settings, mounts, environment, and more.


Executing Commands

Run a command in an existing container:

docker exec -it <container> sh

Restart Policies

Control what happens when a container exits:

docker run --restart=always nginx

Common policies:

  • no – Never restart (default).
  • always – Always restart on failure or reboot.
  • on-failure[:max-retries] – Restart only if the container exits with error.
  • unless-stopped – Restart unless explicitly stopped.

Privileged vs. Unprivileged

  • Unprivileged (default): Container runs with restricted capabilities for better security.

  • Privileged: Grants access to all devices and extended capabilities (similar to root on host). Example:

    docker run --privileged -it alpine sh

Pruning

Remove stopped containers, dangling images, and unused networks:

docker system prune

Remove all unused objects (volumes included):

docker system prune -a --volumes