Material

Docker

Docker is a containerization platform that allows you to package an application with all its dependencies into a standardized unit (container) for development, delivery and execution.

Main advantages:

  • Same environment on all machines
  • Isolating applications from each other
  • Quick start and stop
  • Resource savings compared to VM
  • Easy to scale

Docker structure

Dockerfile → Image → Container

Key Components

  • Dockerfile: instructions for building the image
  • Image: template for creating a container
  • Container: running image instance
  • Registry: image repository (e.g. Docker Hub)

Dockerfile — a text file with instructions for building a Docker image. The instructions are executed by the builder in isolated build containers and form the layers of the image; this is not the same container that is later launched in production.

Here is an example of a simple Dockerfile and an explanation of the basic commands:

# Используем базовый образ
FROM ubuntu:20.04

# Устанавливаем необходимые пакеты
RUN apt-get update && apt-get install -y \
    python3 \
    python3-pip

# Создаем рабочий каталог
WORKDIR /app

# Копируем файлы в контейнер
COPY . /app

# Устанавливаем зависимости Python
RUN pip3 install -r requirements.txt

# Определяем переменные среды
ENV APP_PORT=8000

# Открываем порт
EXPOSE $APP_PORT

# Команда, которая будет выполнена при запуске контейнера
CMD ["python3", "app.py"]
  • FROM: Specifies the base image from which the new image is built.
  • RUN: Executes commands within the image during the build process. In this case, the list of packages is updated and Python and pip are installed.
  • WORKDIR: Sets the working directory for the following instructions.
  • COPY: Copies files from the build context to the image file system.
  • RUN: Installs Python dependencies from a file requirements.txt.
  • ENV: Defines environment variables.
  • EXPOSE: Documents which port the application is listening on. The instruction does not publish the port on the host; they use it for this docker run -p or setting ports in Compose.
  • CMD: Specifies the command that will be executed when the container starts.

Multistage docker:

Multi-stage build - a way to use multiple stages FROM in one Dockerfile. Only the necessary artifacts are copied from the build stage to the final stage, not including compilers and other temporary dependencies.

The basic idea is to use one stage to build the application and another to deploy it. This allows you to ultimately create images that contain only the components necessary for the application to function, excluding redundant dependencies and assembly files.

# syntax=docker/dockerfile:1

FROM alpine:latest AS builder
RUN apk --no-cache add build-base

FROM builder AS build1
COPY source1.cpp source.cpp
RUN g++ -o /binary source.cpp

FROM builder AS build2
COPY source2.cpp source.cpp
RUN g++ -o /binary source.cpp

# docker build --target build1 .

Practical use cases

Running a simple web application

# Dockerfile
FROM python:3.13-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
EXPOSE 8000

CMD ["python", "app.py"]
# Сборка и запуск
docker build -t myapp .
docker run -p 8000:8000 myapp

Development with a database

We use Docker Compose v2, which runs as docker compose. Old standalone binary docker-compose refers to Compose v1.

# compose.yaml
services:
  web:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - .:/app
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 10

volumes:
  postgres_data:

Data storage types

  1. Volumes: persistent storage created and managed by Docker
docker volume create mydata
docker run -v mydata:/data myapp
  1. Bind Mounts: direct connection to the host system
docker run -v /host/path:/container/path myapp
  1. tmpfs: temporary storage in memory (Linux only)
docker run --tmpfs /tmp myapp

Networking in Docker

  • bridge: (default) for containers on the same host
  • host: uses the host network
  • none: without network
  • overlay: connects containers on different Docker hosts participating in Swarm mode
# Создание сети
docker network create mynetwork

# Подключение контейнера к сети
docker run --network mynetwork myapp

Image optimization

Use multi-stage builds

# Этап сборки
FROM node:16 AS builder
WORKDIR /app
COPY . .
RUN npm ci && npm run build

# Финальный этап
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html

Minimize layers

# Плохо
RUN apt-get update
RUN apt-get install -y package1
RUN apt-get install -y package2

# Хорошо
RUN apt-get update && apt-get install -y \\
    package1 \\
    package2

Typical use cases

Local development

# Запуск окружения разработки
docker compose up -d

# Просмотр логов
docker compose logs -f

# Перезапуск сервиса после изменений
docker compose restart web

Debugging

# Подключение к работающему контейнеру
docker exec -it container_id bash

# Просмотр логов
docker logs -f container_id

# Просмотр использования ресурсов
docker stats

Frequently used commands

# Управление контейнерами
docker ps             # Список запущенных контейнеров
docker ps -a          # Все контейнеры
docker start/stop     # Запуск/остановка контейнера
docker rm             # Удаление контейнера

# Управление образами
docker images         # Список образов
docker pull          # Загрузка образа
docker build         # Сборка образа
docker rmi           # Удаление образа

# Работа с Docker Compose
docker compose up    # Запуск сервисов
docker compose down  # Остановка и удаление сервисов
docker compose logs  # Просмотр логов

Docker compose

Docker Compose - a tool for defining and running multi-container applications. The YAML file describes services, networks, volumes, build configuration and other parameters, and the CLI manages the application lifecycle.

Basic Docker Compose Concepts Docker Compose simplifies application development and testing, especially in the context of multi-container scenarios where multiple services need to communicate with each other.

  1. Configuration file (compose.yaml): Docker Compose uses a YAML file to define settings and parameters for each service in a multi-container application. In this file you can specify container images, ports, networks, volumes, environment variables and other settings. Example file compose.yaml:
services:
  web:
    image: nginx:1.28
    ports:
      - "8080:80"
  db:
    image: mysql:8.4
    environment:
      MYSQL_ROOT_PASSWORD: example
  1. Services: Each service in a multi-container application is defined as a separate block in the configuration file. Services can communicate with each other through network connections.
  2. CLI Commands: Docker Compose provides commands docker compose up, docker compose down, docker compose ps and others.
  3. Networks and volumes: Docker Compose allows you to define networks and volumes to enable communication and storage between containers.

Basic Commands

docker run :

Launches a new container from the image.

docker run -it ubuntu:latest /bin/bash

docker ps:

Displays a list of running containers.

docker ps

docker images:

Shows a list of downloaded images.

docker images

docker build:

Builds an image from a Dockerfile.

docker build -t my_image:latest .

docker stop:

Stops the operation of one or more containers.

docker stop container_id

docker rm:

Removes one or more containers.

docker rm container_id

docker rmi:

Deletes one or more images.

docker rmi image_id

docker exec:

Runs a command inside a running container.

docker exec -it container_id /bin/bash

docker compose up:

Launches the application according to the settings in the file compose.yaml.

docker compose up

docker network ls:

Displays a list of Docker networks.

docker network ls

docker pull:

Downloads an image from Docker Hub or another repository.

docker pull nginx:latest

docker logs:

Views container log output.

docker logs container_id

docker inspect:

Returns detailed information about a container, image, network, or volume.

docker inspect container_id

docker compose down:

Stops and deletes the project's containers and networks. Volumes are deleted only with the flag --volumes, and external resources are not deleted.

docker compose down

docker ps -a:

Displays a list of all containers, including stopped ones.

docker ps -a

docker compose build:

Builds images defined in a file compose.yaml.

docker compose build

docker exec -it:

Starts an interactive shell inside a container.

docker exec -it container_id /bin/sh

docker compose logs:

Views the output of service logs from compose.yaml.

docker compose logs

docker volume ls:

Displays a list of created Docker volumes.

docker volume ls

docker compose ps:

Displays the status of services defined in the file compose.yaml.

docker compose ps

What might they ask (theory)

How to create a Docker image?

The Docker image is created using Dockerfile, which provides step-by-step instructions for building an image, including a base image, dependencies, and settings.

What is Docker and what is it used for?

Docker is a platform for containerizing applications. Containers isolate processes and make the environment portable between compatible operating systems and architectures; in doing so, they share the host kernel. Used to deliver and deploy a software solution across devices, simplifying this task.

What is Docker Compose and how does it simplify the deployment of multi-container applications?

Docker Compose is a tool for defining and managing multi-container applications via a YAML configuration file, allowing you to easily launch and scale associated services.

How to manage networks in Docker?

Docker provides commands for creating and managing networks such as docker network create and docker network connect, allowing containers to communicate across isolated network spaces.

What is Docker Hub?

Docker Hub is a cloud-based Docker image registry where developers can publish, share, and download ready-made images for use in their projects.

What is container orchestration and what tools do you know for it?

Container orchestration is the management and deployment of containers in large-scale environments. Kubernetes, Docker Swarm, and Amazon ECS are examples of container orchestration tools.

Advanced questions

How are containers secured in Docker?

Docker provides namespaces, cgroups and capabilities for isolation, but this is not an automatic guarantee of security. We need minimal privileges/capabilities, an unprivileged user, trusted updatable images, Docker socket protection and refusal --privileged, if it is not needed.

What tools can I use to monitor Docker containers?

To monitor Docker containers, you can use tools such as Prometheus, Grafana, cAdvisor, which provide metrics and visualization of the state of containers.

How does Docker affect application performance?

A container is an isolated process that shares the host kernel. The overhead depends on the network, file system, resource limits, and runtime environment, so the impact on a specific workload needs to be measured.

Interview questions: how to construct an honest answer

Below is not a finished story, but options for the structure of the answer. Use only those points that correspond to your real experience: name the context of the task, your actions, limitations and result. If another team was working on the tool, clearly separate their responsibility from yours.

How have you dealt with container failures?

Tell us about the specific failure and diagnostic sequence: checking the container status, docker logs, docker inspect, metrics, healthcheck, network, volumes and resource limits. Conclude your answer with the reason for the failure and how you prevented it from happening again. If this has not happened, describe the diagnostic procedure you are familiar with as a theoretical algorithm.

What are some common problems you've encountered when using Docker in projects?

Select one or two problems that you have actually encountered: environmental differences, invalid variables, volume permissions, lack of memory, healthcheck or network. For example, inside Compose, the application accesses the database by service name and internal port, and from the host - through the published port on localhost. Explain how you found and fixed the problem.

How did you scale the application if you were working with Kubernetes?

Describe only your area of responsibility. For example: “Deployment and Service were supported by the platform team, and I checked the Pods’ logs, changed the agreed upon environment variables or image tag, and controlled the rollout.” If you configured replicas, requests/limits, autoscaling or balancing yourself, name the specific parameters and the observed result. Don't take credit for setting up a cluster if another team did it.

How to answer if you haven’t worked with Kubernetes?

Be direct about it and talk about your near-real experience. If you scaled the service without Kubernetes, you can describe profiling, eliminating bottlenecks, launching additional replicas and balancing via Nginx. If the load remained small, the correct answer was: “The project did not require horizontal scaling; I understand the general approach, but I haven’t set it up in production.”

How did you resolve compatibility issues between development and production environments when using Docker?

Name the actual measures that were used: a single Dockerfile, Compose for local dependencies, fixed versions of images, the same launch commands and configuration verification in CI. Secure example: the repository stores only unclassified .env.example, but real .env and the secrets are transferred by the deployment environment or secret manager.

Which Docker monitoring and logging tools do you prefer and why?

List only tools that you have personally used and explain your task. For example: Prometheus collected metrics, Grafana showed dashboards and alerts, and Elasticsearch/Logstash/Kibana were used to search through logs. If you’ve only read ready-made dashboards and logs, then formulate it that way.

How did you update images in production?

If you worked with Kubernetes, you can describe a real rolling update Deployment: a new image tag, gradual replacement of Pods, maxUnavailable/maxSurge, readiness probes, monitoring rollout and rollback in case of error. Don't call it a canary deployment unless the new version received a separately limited share of traffic. If the update process was carried out by a platform team, describe only your actions - for example, preparing the image and checking the application after upload.

What has been your experience managing configurations and environment variables in containers?

Tell us where the non-secret configuration was stored in your project, how secrets were transferred, who changed the values, and how mandatory variables were checked when the application started. Don't show real secrets or claim that you used a secret manager if you only worked with environment variables.

What benefits have you noticed when using Docker to test and deploy applications?

Provide an observable result from your project: identical run locally and in CI, dependency isolation, reproducible testbed, or more predictable delivery. Scaling is not an automatic benefit of Docker alone - it requires a separate infrastructure.

What have been your approaches to optimizing the size of Docker images and reducing resource consumption?

Select the techniques you have used and add a measurable result if there is one: a suitable minimal base image, multi-stage build, .dockerignore, reproducible installation of dependencies and removal of build files from the final image. Alpine is not always suitable: for Python packages with native dependencies, Debian slim may be smaller in the final result and easier to build. Do not claim a specific size reduction without measurements.

Official sources

  • Dockerfile reference
  • Multi-stage builds
  • Building best practices
  • Docker Compose