build создать свой Docker контейнер

Содержание
Введение
Основы
Явно указать Dockerfile
Справка
Статьи про Docker

Введение

Частой задачей для настройки окружения является создание своих контейнеров.

Основы

Первым делом создайте файл с настройками Docker - Dockerfile и отредактируйте его, например, с помощью редактора vim

touch Dockerfile
vi Dockerfile

FROM debian RUN apt -y update

Теперь нужно собрать образ для этого и нужна команда build

docker build -t andrei-debian:1.0 .

-t это сокращение от --tag задаёт название и тэг в формате 'name:tag'

тэг можно не указывать - это опционально

. означает - в текущей директории

Проверить наличие этого образа в списке можно командой images

docker images

REPOSITORY TAG IMAGE ID CREATED SIZE andrei-debian 1.0 034af79c78c2 4 minutes ago 142MB debian latest a11311205db1 27 hours ago 124MB

Появился скачанный образ debian и образ andrei-debian, только что созданный на его основе.

Теперь запустите его командой run

docker run --name debian1 andrei-debian:1.0

Контейнер запустится и сразу же выключится, потому что в нём нет никаких процессов

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 97f8baddbe9f andrei-debian:1.0 "bash" 6 seconds ago Exited (0) 5 seconds ago debian1

docker run -it --name debian1 andrei-debian:1.0

Появится приветствие терминала внутри контейнера

Откройте новый терминал и убедитесь, что статус контейнера Up

docker ps -a

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e901ad90703c andrei-debian:1.0 "bash" 9 seconds ago Up 9 seconds debian1

Явно указать Dockerfile

Если в одной директории находится несколько докерфайлов можно явно указать какой из них следует использовать для сборки.

Для этого используется флаг -f

docker build -t andrei-debian:1.0 -f Dockerfile.debian .

Называть докерфайлы нужно в соответсвии с документацией :

Dockerfile.name

Например, я создаю свой образ на основе Ubuntu и с тестами на PyTest следующей командой

docker build --tag pytest_ubuntu:1.0 -f ./dockerfiles/Dockerfile.ubuntu .

Образ будет называться pytest_ubuntu и иметь тег 1.0

docker images

REPOSITORY TAG IMAGE ID CREATED SIZE pytest_ubuntu 1.0 eb4761442740 About an hour ago 1.79GB

Справка

docker build --help

Usage: docker build [OPTIONS] PATH | URL | - Build an image from a Dockerfile Options: --add-host list Add a custom host-to-IP mapping (host:ip) --build-arg list Set build-time variables --cache-from strings Images to consider as cache sources --cgroup-parent string Optional parent cgroup for the container --compress Compress the build context using gzip --cpu-period int Limit the CPU CFS (Completely Fair Scheduler) period --cpu-quota int Limit the CPU CFS (Completely Fair Scheduler) quota -c, --cpu-shares int CPU shares (relative weight) --cpuset-cpus string CPUs in which to allow execution (0-3, 0,1) --cpuset-mems string MEMs in which to allow execution (0-3, 0,1) --disable-content-trust Skip image verification (default true) -f, --file string Name of the Dockerfile (Default is 'PATH/Dockerfile') --force-rm Always remove intermediate containers --iidfile string Write the image ID to the file --isolation string Container isolation technology --label list Set metadata for an image -m, --memory bytes Memory limit --memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap --network string Set the networking mode for the RUN instructions during build (default "default") --no-cache Do not use cache when building the image --pull Always attempt to pull a newer version of the image -q, --quiet Suppress the build output and print image ID on success --rm Remove intermediate containers after a successful build (default true) --security-opt strings Security options --shm-size bytes Size of /dev/shm -t, --tag list Name and optionally a tag in the 'name:tag' format --target string Set the target build stage to build. --ulimit ulimit Ulimit options (default [])