Skip to content
>_KernelBrief
Software Development

Docker for Beginners: Images, Containers and Your First Dockerfile

Learn Docker from scratch: what images and containers are, the commands you need, and how to write, build and run your first Dockerfile safely.

By Published Updated 11 min read
// DEV
Table of contents

Docker lets you package an application together with everything it needs to run — the language runtime, libraries, system packages and configuration — into an image, and then start that image as an isolated container on any machine with Docker installed. To get started you need three things: Docker installed, a handful of commands (docker run, docker build, docker ps), and a Dockerfile that describes how to build your image. This guide walks through all three with a small working example.

If you have ever said "it works on my machine", Docker is the tool built to make that sentence irrelevant.

What Docker actually solves

Before containers, running an app on a new machine meant reproducing its environment by hand: the right Python or Node version, the right system libraries, the right environment variables. Every difference between your laptop, a colleague's laptop and the server was a chance for something to break.

Docker moves that environment into a file that lives in your repository. The same image gives you the same files, libraries and settings in development, in CI and in production, so "works on my machine" problems mostly disappear (differences in CPU architecture, host kernel or resource limits can still matter). That is also why tools such as Python virtual environments and Docker complement each other: a venv isolates Python packages on one machine, while a container isolates the whole runtime, including the operating system userland.

Containers vs virtual machines

A virtual machine emulates a complete computer and runs its own full operating system kernel. A container does not: it shares the host's kernel and isolates only processes, filesystem, network and resources using kernel features. The practical results:

  • Containers start in seconds or less, because there is no operating system to boot.
  • Images are usually tens to hundreds of megabytes instead of gigabytes.
  • You can run many containers on one machine with little overhead.
  • Isolation is weaker than a VM's, because every container shares one kernel. That matters for security decisions, which is why the "run as non-root" advice later in this guide is important.

Images, containers, registries: the core concepts

Four terms cover most of what you need:

Concept What it is Analogy
Image A read-only, layered template: base OS files, runtime, your code, and the default command to run A class, or a recipe
Container A running or stopped instance of an image, with its own writable layer An object, or the cooked dish
Dockerfile A text file of instructions that builds an image The recipe card
Registry A server that stores and distributes images, such as Docker Hub A package repository

Images are built in layers. Each instruction in a Dockerfile that changes the filesystem (RUN, COPY, ADD) adds a layer, and Docker caches layers so that unchanged steps are not rebuilt. Understanding this cache is the single most useful thing for writing fast builds, and we come back to it below.

Images are also identified by a name and tag, for example python:3.14-slim: the repository is python, the tag is 3.14-slim. If you omit the tag, Docker assumes latest, which is rarely what you want in a real project because it changes over time.

Installing Docker

  • Windows and macOS: install Docker Desktop, which bundles the Docker Engine (running inside a lightweight Linux VM), the CLI, Docker Compose and a GUI.
  • Linux: you can install Docker Engine directly from your distribution's packages or Docker's own repository, or use Docker Desktop for Linux.

Check licensing before you install at work. According to Docker's license page, Docker Desktop is free for personal use, education, non-commercial open source and small businesses with fewer than 250 employees and less than $10 million in annual revenue (both conditions apply). Larger companies and government entities need a paid Pro, Team or Business subscription.

Once installed, confirm everything works:

docker version
docker run hello-world

docker run hello-world downloads a tiny test image from Docker Hub, starts a container from it, prints a message and exits. If you see the greeting, your installation is working.

The essential Docker commands

You will use these constantly:

# Download an image without running it
docker pull python:3.14-slim

# Run an interactive container and remove it when you exit
docker run -it --rm python:3.14-slim python

# Run a web server in the background, mapping host port 8080 to container port 80
docker run -d --name web -p 8080:80 nginx

# List running containers (add -a to include stopped ones)
docker ps
docker ps -a

# See a container's output, follow it live with -f
docker logs -f web

# Open a shell inside a running container
docker exec -it web sh

# Stop and remove a container
docker stop web
docker rm web

# List and remove images
docker images
docker rmi nginx

A few flags do most of the work:

  • -d runs the container detached (in the background).
  • -it gives you an interactive terminal.
  • --rm deletes the container automatically when it stops — ideal for throwaway experiments.
  • -p HOST:CONTAINER publishes a port. In -p 8080:80, you browse to localhost:8080 and traffic reaches port 80 inside the container.
  • --name gives the container a readable name instead of a random one.
  • -e KEY=value sets an environment variable.
  • -v mounts a volume or a host folder (covered below).

Writing your first Dockerfile

Let's containerise a tiny Python web server. It uses only the standard library, so there are no dependencies to install. Create a new folder with this app.py:

from http.server import BaseHTTPRequestHandler, HTTPServer


class Hello(BaseHTTPRequestHandler):
    def do_GET(self):
        body = b"Hello from a Docker container!\n"
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


if __name__ == "__main__":
    print("Listening on port 8000", flush=True)
    HTTPServer(("0.0.0.0", 8000), Hello).serve_forever()

Note the 0.0.0.0 bind address. A server listening only on 127.0.0.1 inside a container is unreachable from outside it, which is one of the most common beginner mistakes.

Now add a file named Dockerfile (no extension) next to it:

# syntax=docker/dockerfile:1
FROM python:3.14-slim

WORKDIR /app

# Create an unprivileged user to run the app
RUN useradd --create-home --uid 10001 appuser

COPY app.py .

USER appuser
EXPOSE 8000
CMD ["python", "app.py"]

What each instruction does:

  • FROM picks the base image. python:3.14-slim is the official Python image on a slimmed-down Debian base.
  • WORKDIR sets (and creates) the working directory for the following instructions and for the running container.
  • RUN executes a command at build time and saves the result as a new layer. Here it creates a non-root user.
  • COPY copies files from your project (the build context) into the image.
  • USER switches to that unprivileged user for everything after it, including the running app. Docker's best-practices guide recommends exactly this whenever a service can run without root privileges.
  • EXPOSE documents which port the app listens on. It does not publish the port by itself; -p does that.
  • CMD is the default command. Use the JSON "exec form" shown here, which Docker's documentation recommends in almost all cases: the process then runs directly as PID 1 and receives stop signals properly.

Add a .dockerignore file

When you build, Docker sends the folder's contents (the build context) to the builder. A .dockerignore file, with the same pattern syntax as .gitignore, keeps junk and secrets out of it:

.git
__pycache__/
*.pyc
.venv/
.env

Excluding .env matters: anything in the build context can be copied into an image by a careless COPY . ., and anyone who pulls the image can then read it.

Build and run your image

From the folder containing the Dockerfile:

# Build an image and tag it hello-docker:1.0
docker build -t hello-docker:1.0 .

# Run it, mapping host port 8080 to the container's port 8000
docker run -d --name hello -p 8080:8000 hello-docker:1.0

# Test it
curl http://localhost:8080/

You should see Hello from a Docker container!. The final . in docker build is the build context — the current directory.

Inspect and clean up:

docker logs hello          # shows "Listening on port 8000" and request logs
docker exec hello whoami   # prints appuser, not root
docker stop hello && docker rm hello

To change the app, edit app.py, rebuild with a new tag (for example 1.1) and run a new container. Containers are meant to be replaced, not patched in place.

Make builds fast: order layers for the cache

Docker reuses a cached layer only if the instruction and its inputs are unchanged — and once one layer changes, every layer after it is rebuilt. So put things that change rarely near the top and your frequently edited code at the bottom.

For a real Python app with dependencies, the standard pattern is to copy the dependency list first:

# syntax=docker/dockerfile:1
FROM python:3.14-slim

WORKDIR /app
RUN useradd --create-home --uid 10001 appuser

# 1. Dependencies: only rebuilt when requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 2. Application code: changes often, so it comes last
COPY . .

USER appuser
EXPOSE 8000
CMD ["python", "app.py"]

Editing your code now reuses the cached pip install layer, so rebuilds skip the slow dependency install and only redo the steps after it. The same idea applies to package.json and npm ci in Node projects, or go.mod and go mod download in Go.

If you need system packages on a Debian or Ubuntu base, Docker's guide says to always combine apt-get update and apt-get install in one RUN instruction — otherwise a cached, stale update layer can cause failed or outdated installs:

RUN apt-get update && apt-get install -y --no-install-recommends \
        curl \
    && rm -rf /var/lib/apt/lists/*

Keeping data: volumes and bind mounts

A container's writable layer disappears when the container is removed. For anything you want to keep, mount storage from outside:

# Named volume managed by Docker (good for databases)
docker volume create pgdata
# Keep the password out of the command line: put it in an env file
# (demo value only; add db.env to .gitignore and .dockerignore)
echo "POSTGRES_PASSWORD=change-me" > db.env
docker run -d --name db --env-file db.env \
  -v pgdata:/var/lib/postgresql/data postgres:17

# Bind mount a host folder (good for live-editing code in development)
docker run -it --rm -v "$(pwd)":/app -w /app python:3.14-slim python app.py

Named volumes survive docker rm and can be reattached to a new container. Bind mounts map a real folder on your machine into the container, so edits on either side are visible immediately. Never put real passwords on the command line or in a Dockerfile in production — use your platform's secrets mechanism instead.

Beginner mistakes to avoid

  • Using latest everywhere. Tags are mutable. Pin a specific version tag such as python:3.14-slim; for strict reproducibility, Docker's guide suggests pinning the image to a digest (python:3.14-slim@sha256:...) and updating it with a tool such as Dependabot.
  • Running as root. It is the default unless you add a USER. Containers share the host kernel, so limit what a compromised process can do.
  • Baking secrets into images. Anything copied or set with ENV at build time is readable by anyone with the image. Use .dockerignore and inject secrets at runtime.
  • Binding to 127.0.0.1 inside the container. Listen on 0.0.0.0 and publish the port with -p.
  • Huge images. Start from a slim or minimal base, avoid installing build tools you do not need at runtime, and look at multi-stage builds once you compile code: they let you build in one stage and copy only the result into a small final image.
  • Treating containers like servers. Do not SSH in and hand-edit files. Change the Dockerfile, rebuild, redeploy. Keep that Dockerfile under version control alongside your code — if you work on branches, our guide to Git merge vs rebase covers how to keep that history clean.

Where to go next

Once single containers feel comfortable, the natural next steps are:

  1. Docker Compose, to define multi-container apps (for example a web app plus a database) in one compose.yaml file and start them with docker compose up.
  2. Multi-stage builds, to produce small production images.
  3. Pushing to a registry (Docker Hub, GitHub Container Registry or your cloud provider's registry) with docker tag and docker push, so servers and CI pipelines can pull your image.
  4. Orchestration with Kubernetes or a managed container service — but only when you actually need to run many containers across many machines.

If you will be pushing to registries or deploying to servers over SSH, set up key-based authentication first; our guide on generating Ed25519 SSH keys covers Windows, macOS and Linux.

Frequently asked questions

+What is the difference between a Docker image and a container?

An image is a read-only template that contains an application and everything it needs to run. A container is a running (or stopped) instance created from that image, with its own thin writable layer on top. You can start many containers from one image.

+Is Docker Desktop free?

Docker Desktop is free for personal use, education, non-commercial open source projects and small businesses with fewer than 250 employees and less than $10 million in annual revenue. Larger organisations and government entities need a paid subscription. Docker Engine on Linux is a separate product and is not covered by that license.

+Do I lose my data when a container is removed?

Yes, anything written inside the container's own filesystem is deleted with the container. Store data you want to keep in a named volume or a bind-mounted folder on the host instead.

+Should I use Alpine or slim base images?

Both are small. Alpine is the smallest but uses musl instead of glibc, which can cause compatibility issues with some compiled packages, especially Python wheels. Debian-based slim images are a safer default for beginners; switch to Alpine once you know your dependencies work on it.

Sources & references

  1. Docker Docs — Building best practices
  2. Docker Docs — Docker Desktop license agreement

Spotted an error? See our Corrections Policy.

  • #docker
  • #containers
  • #dockerfile
  • #devops
  • #docker-images
  • #beginners
Dipak Suryawanshi

Dipak SuryawanshiFounder & Editor

Dipak Suryawanshi is a backend developer who works with Java and Spring Boot, focused on building APIs, clean architectures and developer tools. He founded KernelBrief, an independent technology publication based in India, sets its editorial direction and is responsible for everything published on it. Every KernelBrief article is researched and checked against primary sources such as official documentation, vendor advisories and release notes before it is published.