🎢 Что такое Dockerfile и как создать образ Docker?

by itisgood

При работе над проектами Docker большую часть времени существующие образы Docker не соответствуют вашим требованиям.

Вот где Dockerfile вступает в игру; он поможет вам создавать собственные образа Docker.

Следовательно, знание Dockerfile необходимо.

Что такое Dockerfile?

Это простой текстовый файл с набором команд или инструкций.

Эти команды / инструкции выполняются последовательно для выполнения действий с базовым образом для создания нового образа докера.

комментарии и команды + аргументы – это два вида блоков основной строки в синтаксисе Dockerfile.

Синтаксис комментариев

#блоки, используемые для комментирования

command argument argument1 …..
Пример команд + аргументов
#блоки, используемые для комментирования

command argument argument1 …..

Ниже показано, как будет выглядеть ваш рабочий процесс.

  • Создайте Dockerfile и упомяните инструкции по созданию образа Docker.
  • Запустите команду docker build, которая создаст образ docker
  • Теперь образ docker готов к использованию, используйте команду docker run для создания контейнеров.

Основные команды

FROM – Определяет базовый образ для использования и запускает процесс сборки.

RUN – для запуска команды из образа требуется команда и ее аргументы.

CMD – функция, аналогичная команде RUN, но она выполняется только после создания экземпляра контейнера.

ENTRYPOINT – Нацеливается на ваше приложение по умолчанию на изображении при создании контейнера.

ADD – копирует файлы из источника в место назначения (внутри контейнера).

ENV – Устанавливает переменные среды.

Как создать образ Docker с помощью Dockerfile?

Во-первых, давайте создадим Dockerfile.

$ gedit Dockerfile

Поместите показанные ниже команды / инструкции в этот файл и сохраните его.

# Установите базовый образ Ubuntu
FROM ubuntu

# Обновить список источников репозитория и установить gnupg2
RUN apt-get update && apt-get install -y gnupg2

# Добавьте ключ подтверждения пакета
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

# Добавить MongoDB в список источников репозитория
RUN echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' > tee /etc/apt/sources.list.d/mongodb.list

# Update the repository sources list
RUN apt-get update

#  Установить пакет MongoDB (.deb)
RUN apt-get install -y mongodb

# Создать каталог данных по умолчанию
RUN mkdir -p /data/db

#  Выставить порт по умолчанию
EXPOSE 27017

# Порт по умолчанию для выполнения точки входа (MongoDB)
CMD ["--port 27017"]

# Установить команду контейнера по умолчанию
ENTRYPOINT usr/bin/mongodb

В этом Dockerfile Ubuntu устанавливается в качестве базового образа.

Затем упоминаются необходимые команды и аргументы для установки MongoDB.

Порт 27017 открыт для MongoDB с помощью команды контейнера по умолчанию как usr/bin/mongodb

Запуск Dockerfile

Следующая команда создаст образ Docker с именем geekflare_mongodb после успешного выполнения.

$ docker build -t geekflare_mongodb .

Sending build context to Docker daemon  667.2MB

Step 1/9 : FROM ubuntu

latest: Pulling from library/ubuntu

7413c47ba209: Pull complete

0fe7e7cbb2e8: Pull complete

1d425c982345: Pull complete

344da5c95cec: Pull complete

Digest: sha256:c303f19cfe9ee92badbbbd7567bc1ca47789f79303ddcef56f77687d4744cd7a

Status: Downloaded newer image for ubuntu:latest

---> 3556258649b2

Step 2/10 : RUN apt-get update && apt-get install -y gnupg2

---> Running in de3706328761

Get:1 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]

Get:2 http://archive.ubuntu.com/ubuntu bionic InRelease [242 kB]

Fetched 16.9 MB in 38s (445 kB/s)

Reading package lists...

Reading package lists...

Building dependency tree...

Reading state information...

Need to get 5187 kB of archives.

After this operation, 15.8 MB of additional disk space will be used.

Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 readline-common all 7.0-3 [52.9 kB]

Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 libreadline7 amd64 7.0-3 [124 kB]

Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libsqlite3-0 amd64 3.22.0-1ubuntu0.1 [497 kB]

Get:4 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libssl1.1 amd64 1.1.1-1ubuntu2.1~18.04.4 [1300 kB]

debconf: delaying package configuration, since apt-utils is not installed

Fetched 5187 kB in 12s (416 kB/s)

Selecting previously unselected package readline-common.

(Reading database ... 4040 files and directories currently installed.)

Preparing to unpack .../00-readline-common_7.0-3_all.deb ...

Unpacking readline-common (7.0-3) ...

Selecting previously unselected package libreadline7:amd64.

Preparing to unpack .../01-libreadline7_7.0-3_amd64.deb ...

Selecting previously unselected package dirmngr.

Setting up libnpth0:amd64 (1.5-3) ...

Setting up libksba8:amd64 (1.3.5-2) ...

Setting up gnupg-l10n (2.2.4-1ubuntu1.2) ...

Processing triggers for libc-bin (2.27-3ubuntu1) ...

Removing intermediate container de3706328761

---> a32533894ed1

Step 3/10 : RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

---> Running in 69c4dba38983

Warning: apt-key output should not be parsed (stdout is not a terminal)

Executing: /tmp/apt-key-gpghome.MuT5BDWwKZ/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

gpg: key 5F8F93707F0CEB10: public key "Totally Legit Signing Key <mallory@example.org>" imported

gpg: key 9ECBEC467F0CEB10: 1 signature not checked due to a missing key

gpg: key 9ECBEC467F0CEB10: public key "Richard Kreuter <richard@10gen.com>" imported

gpg: Total number processed: 2

gpg:               imported: 2

Removing intermediate container 69c4dba38983

---> cffbe06c1b50

Step 4/10 : RUN echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' > tee /etc/apt/sources.list.d/mongodb.list

---> Running in 40630fd7b0a9

Removing intermediate container 40630fd7b0a9

---> a1bd9d8d7e51

Step 5/10 : RUN apt-get update

---> Running in 750717d9c0ea

Hit:1 http://archive.ubuntu.com/ubuntu bionic InRelease

Hit:2 http://archive.ubuntu.com/ubuntu bionic-updates InRelease

Hit:3 http://security.ubuntu.com/ubuntu bionic-security InRelease

Hit:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease

Reading package lists...

Removing intermediate container 750717d9c0ea

---> 397d6501db58

Step 6/10 : RUN apt-get install -y mongodb

---> Running in 88609c005e73

Reading package lists...

Building dependency tree...

Reading state information...

The following NEW packages will be installed:

libboost-filesystem1.65.1 libboost-iostreams1.65.1

libboost-program-options1.65.1 libboost-system1.65.1 libgoogle-perftools4

libpcap0.8 libpcrecpp0v5 libsnappy1v5 libstemmer0d libtcmalloc-minimal4

libunwind8 libyaml-cpp0.5v5 mongo-tools mongodb mongodb-clients

mongodb-server mongodb-server-core

0 upgraded, 17 newly installed, 0 to remove and 0 not upgraded.

Need to get 53.7 MB of archives.

After this operation, 218 MB of additional disk space will be used.

Get:1 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 mongodb-clients amd64 1:3.6.3-0ubuntu1.1 [20.2 MB]

Get:2 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 mongodb-server-core amd64 1:3.6.3-0ubuntu1.1 [20.3 MB]

Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 mongodb-server all 1:3.6.3-0ubuntu1.1 [12.6 kB]

Get:4 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 mongodb amd64 1:3.6.3-0ubuntu1.1 [9968 B]

Fetched 53.7 MB in 10s (5485 kB/s)

Selecting previously unselected package libpcap0.8:amd64.

(Reading database ... 4390 files and directories currently installed.)

Selecting previously unselected package mongodb-clients.

Preparing to unpack .../13-mongodb-clients_1%3a3.6.3-0ubuntu1.1_amd64.deb ...

Unpacking mongodb-clients (1:3.6.3-0ubuntu1.1) ...

Selecting previously unselected package mongodb-server-core.

Preparing to unpack .../14-mongodb-server-core_1%3a3.6.3-0ubuntu1.1_amd64.deb ...

Unpacking mongodb-server-core (1:3.6.3-0ubuntu1.1) ...

Selecting previously unselected package mongodb-server.

Preparing to unpack .../15-mongodb-server_1%3a3.6.3-0ubuntu1.1_all.deb ...

Unpacking mongodb-server (1:3.6.3-0ubuntu1.1) ...

Selecting previously unselected package mongodb.

Preparing to unpack .../16-mongodb_1%3a3.6.3-0ubuntu1.1_amd64.deb ...

Unpacking mongodb (1:3.6.3-0ubuntu1.1) ...

Setting up mongodb-server-core (1:3.6.3-0ubuntu1.1) ...

Setting up mongo-tools (3.6.3-0ubuntu1) ...

Setting up mongodb-clients (1:3.6.3-0ubuntu1.1) ...

Setting up mongodb-server (1:3.6.3-0ubuntu1.1) ...

invoke-rc.d: could not determine current runlevel

invoke-rc.d: policy-rc.d denied execution of start.

Setting up mongodb (1:3.6.3-0ubuntu1.1) ...

Processing triggers for libc-bin (2.27-3ubuntu1) ...

Removing intermediate container 88609c005e73

---> d9c072cb1f84

Step 7/10 : RUN mkdir -p /data/db

---> Running in f817778f69ab

Removing intermediate container f817778f69ab

---> a3fbdb3def5c

Step 8/10 : EXPOSE 27017

---> Running in 8d070e2a1e07

Removing intermediate container 8d070e2a1e07

---> f770776a538c

Step 9/10 : CMD ["--port 27017"]

---> Running in ab612410df77

Removing intermediate container ab612410df77

---> e5830b80934f

Step 10/10 : ENTRYPOINT usr/bin/mongod

---> Running in 95f574727aab

Removing intermediate container 95f574727aab

---> 095d17727ca0

Successfully built 095d17727ca0

Successfully tagged geekflare_mongodb:latest

Давайте проверим, создался ли образ Docker с именем geekflare mongodb.

~$ docker images

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE

geekflare_mongodb          latest              095d17727ca0        3 minutes ago       325MB

ubuntu                     latest              3556258649b2        4 days ago          64.2MB

mean_express               latest              35dcb3df9806        6 days ago          923MB

mean_angular               latest              9f8d61db600c        6 days ago          1.29GB

Запустите образ Docker geekflare_mongodb внутри контейнера mongo_container.

 docker run --name mongo_container -i -t geekflare_mongodb

2019-07-27T19:38:23.734+0000 I CONTROL  [initandlisten] MongoDB starting : pid=6 port=27017 dbpath=/data/db 64-bit host=b0095c1e5536

2019-07-27T19:38:23.735+0000 I CONTROL  [initandlisten] db version v3.6.3

2019-07-27T19:38:23.735+0000 I CONTROL  [initandlisten] git version: 9586e557d54ef70f9ca4b43c26892cd55257e1a5

2019-07-27T19:38:23.736+0000 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.1.1  11 Sep 2018

2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten] allocator: tcmalloc

2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten] modules: none

2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten] build environment:

2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten]     distarch: x86_64

2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten]     target_arch: x86_64

2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten] options: {}

2019-07-27T19:38:23.745+0000 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=2038M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),statistics_log=(wait=0),verbose=(recovery_progress),

2019-07-27T19:38:24.733+0000 I CONTROL  [initandlisten]

2019-07-27T19:38:24.734+0000 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.

2019-07-27T19:38:24.735+0000 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.

2019-07-27T19:38:24.736+0000 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.

2019-07-27T19:38:24.736+0000 I CONTROL  [initandlisten]

2019-07-27T19:38:24.736+0000 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.

2019-07-27T19:38:24.737+0000 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server.

2019-07-27T19:38:24.737+0000 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP

2019-07-27T19:38:24.737+0000 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to

2019-07-27T19:38:24.737+0000 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the

2019-07-27T19:38:24.738+0000 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.

2019-07-27T19:38:24.738+0000 I CONTROL  [initandlisten]

2019-07-27T19:38:24.739+0000 I STORAGE  [initandlisten] createCollection: admin.system.version with provided UUID: 4b8b509d-633a-46c1-a302-cb8c82b0d5d3

2019-07-27T19:38:24.788+0000 I COMMAND  [initandlisten] setting featureCompatibilityVersion to 3.6

2019-07-27T19:38:24.818+0000 I STORAGE  [initandlisten] createCollection: local.startup_log with generated UUID: 6c1c0366-4b1b-4b92-9fcd-d18acc126072

2019-07-27T19:38:24.862+0000 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'

2019-07-27T19:38:24.866+0000 I NETWORK  [initandlisten] waiting for connections on port 27017

Откройте новый терминал и проверьте, работает ли mongo_container.

$ docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES

b0095c1e5536        geekflare_mongodb   "/bin/sh -c usr/bin/…"   35 seconds ago      Up 33 seconds       27017/tcp           mongo_container

Как видите, контейнер, созданный из образа geekflare mongodb, запущен и работает.

You may also like

Leave a Comment