Top.Mail.Ru

Guide to basic commands in Docker

Guide to basic commands in Docker

Docker has long been the standard tool for containerizing applications, and this material will help you understand the basic commands that are needed for everyday work.

How Docker commands work

Most Docker commands follow a simple pattern: docker + command and additional parameters and flags.

It’s best to start with the commands that are useful in any console utility: viewing the version and built-in help.

Check Docker version:

docker --version

Open general Docker help:

docker --help

If you need to understand a specific command in more detail, you can request help for that specific command so you can see all the available flags and use cases. For example, for run:

docker run --help

Working with Docker images

Images are the basis of containers. Inside the image is everything needed to run the application: code, execution environment, libraries and dependencies.

Next, we will show the key commands that help you search, download, build and delete images.

Search for images

Before you can use the image, you need to find it in the registry. By default, Docker runs with Docker Hub, where thousands of ready-made images are available.

Search for example nginx:

sudo docker search nginx

The command will show a list of found options with a description and rating indicators. This makes it easier to choose a popular and supported image.

Loading (pull) images

When the desired image is found, it can be downloaded to the server. To download the latest version:

sudo docker pull nginx

If you need a specific version, please indicate this:

sudo docker pull nginx:1.25.3

Viewing Local Images

To see all the images that are already on the system, run the command:

sudo docker images

Typically the output includes the repository name, tag, image ID, creation date, and size.

Assembling your image

If you need your own image, it is usually assembled from Dockerfile. Example of a simple Dockerfile in the current folder:

FROM ubuntu:24.04

RUN apt update && apt install -y nginx

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

This Dockerfile creates an image based on Ubuntu 24.04, installs Nginx and runs it as a web server.

Build the image:

sudo docker build -t myapp:1.0 .

The -t flag specifies the name and version (tag). The dot at the end means that the build context is the current directory, and Docker will look for the Dockerfile there.

Removing images

To remove an unnecessary image:

sudo docker rmi nginx:latest

If the image is being used by a running or stopped container, Docker will prevent it from being deleted. Then first delete the container, or use forced deletion:

docker rm container_name

docker rmi -f nginx:latest

Docker container management

A container is a running instance of an image. For practical work, it is important to be able to launch containers, look at the list, stop, restart and delete.

Running a container

The easiest way to launch a container from an image:

sudo docker run nginx

But this way the container runs in the “foreground” and occupies the terminal. In real work, the background mode is often used:

sudo docker run -d nginx

It is also convenient to forward ports and give the container a clear name:

sudo docker run -d -p 8080:80 --name my-webserver nginx

Here -d runs in the background, -p 8080:80 maps port 8080 on the host to port 80 inside the container, and —name sets the name my-webserver.

List of containers

Show only running containers:

sudo docker ps

Show all containers, including stopped ones:

sudo docker ps -a

Stopping, starting and restarting

First, they usually look at what containers are in the system:

sudo docker ps -a

Stop container:

sudo docker stop my-webserver

Start a stopped container:

sudo docker start my-webserver

Restart container (stop + start):

sudo docker restart my-webserver

Removing containers

Remove container:

sudo docker rm test

If the container is running, Docker will not allow you to delete it without additional steps. There are two options: stop first, or force delete:

sudo docker rm -f test

The -f flag terminates the container immediately, without a soft shutdown, so it is better to use it deliberately.

Monitoring and Debugging Containers

To keep containers in working order and quickly deal with problems, it is useful to know a few commands for logging, accessing inside the container, and diagnostics.

Viewing logs

Show container logs:

sudo docker logs awesome_heyrovsky

Monitor logs in real time (analogous to tail -f):

sudo docker logs -f awesome_heyrovsky

Executing commands inside a container

One of the most convenient Docker tools is the ability to go inside a running container and execute commands directly in its environment:

sudo docker exec -it test /bin/bash

The -it flags open an interactive terminal so you can touch files, view configs, and debug application behavior.

Viewing detailed information about a container

The inspect command displays detailed information about the container in JSON: configuration, network, volumes, environment variables and current state.

sudo docker inspect test

Load and resource consumption

See how much CPU/RAM and I/O containers use in real time:

sudo docker stats

Docker cleanup and maintenance

Over time, Docker accumulates stopped containers, unused images, networks, and other tails. Periodic cleaning helps free up space and keep your surroundings tidy.

Delete all stopped containers:

sudo docker container prune

Remove unused images:

sudo docker image prune

Now you know the basic set of Docker commands, which covers the main tasks: finding and downloading images, launching and managing containers, viewing logs and diagnostics, and maintaining order through regular cleanup.

CONTENT:

Similar

All news

Похожее

Все новости

Adaxa Suite: подробный обзор ERP-системы корпоративного класса

Adaxa Suite — комплексная ERP-платформа для компаний, которым уже тесно в рамках простых учётных систем, но которые при этом не готовы идти в сторону дорогих корпоративных решений уровня SAP или Oracle. Изначально продукт создавался для среднего бизнеса, которому нужна большой набор функций, сквозная автоматизация процессов и надёжная архитектура без чрезмерной стоимости владения. Архитектура и техническая […]

Как заказать дополнительные IP-адреса на UFO.Hosting: пошаговая инструкция

По мере роста проекта одного IP-адреса может стать недостаточно. Это типичная ситуация для компаний, которые масштабируют инфраструктуру, запускают новые сервисы или разделяют внутренние процессы. В UFO.Hosting подключение дополнительных IP-адресов выполняется через биллинговую панель и занимает всего несколько минут. Важно: возможность для заказа дополнительных IP-адресов доступна для тарифов VPS начиная с Haedus. Зачем нужны дополнительные IP-адреса […]