Centos docker with windows

Установка и использование Docker в CentOS 7

Docker – это популярное приложение для контейнеризации процессов программ. Такие контейнеры – это, по сути, виртуальные машины с высокой портативностью, которые более рационально используют ресурсы и в большей степени зависят от операционной системы.

Существует два метода установки Docker в CentOS 7. Первый метод подразумевает установку программы в существующую операционную систему, второй – установку программы при помощи инструмента Docker Machine.

Данное руководство поможет установить и подготовить к работе Docker в текущей операционной системе.

Требования

  • 64-битный сервер CentOS 7.
  • Не-root пользователь с доступом к sudo (инструкции по настройке такого аккаунта – здесь). Все команды в руководстве следует выполнять в сессии такого пользователя (если не сказано другое).

Примечание: Для работы программы Docker необходима 64-битная версия CentOS 7 и ядро версии 3.10+.

1: Установка Docker

Пакет Docker можно найти в официальном репозитории CentOS 7, однако этот пакет, скорее всего, будет устаревшим. Чтобы получить наиболее актуальную версию программы, нужно обратиться к официальному репозиторию Docker.

В этом разделе показано, как загрузить и установить пакет из официального репозитория Docker.

Обновите индекс пакетов:

sudo yum check-update

Теперь можно загрузить и установить пакет Docker. Для этого запустите:

curl -fsSL https://get.docker.com/ | sh

После завершения установки запустите демон Docker:

sudo systemctl start docker

Чтобы убедиться в том, что программа работает, запросите её состояние:

sudo systemctl status docker

docker.service — Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2016-05-01 06:53:52 CDT; 1 weeks 3 days ago
Docs: https://docs.docker.com
Main PID: 749 (docker)

Теперь в системе работает сервис Docker (или демон). Также у вас есть доступ к утилите командной строки docker (это клиент Docker).

2: Настройка команды docker (опционально)

По умолчанию команда docker требует привилегий root (или доступа к команде sudo). Также её можно запускать в группе docker, которая создаётся автоматически во время установки программы Docker.

Если вы попытаетесь запустить команду docker без префикса sudo и вне группы docker, вы получите ошибку:

docker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.
See ‘docker run —help’.

Чтобы вам не пришлось набирать префикс sudo каждый раз, когда вам нужно запустить команду docker, добавьте своего пользователя в группу docker:

sudo usermod -aG docker $(whoami)

Чтобы активировать это изменение, выйдите из системы и войдите снова.

Чтобы добавить в группу docker пользователя, который не является текущим, укажите в команде его имя:

sudo usermod -aG docker username

Примечание: Далее в руководстве предполагается, что команда docker запускается пользователем, который состоит в группе docker. В противном случае вам нужно добавлять префикс sudo самостоятельно.

3: Использование команды Docker

Итак, программа контейнеризации Docker установлена и готова к работе. Использование команды docker заключается в передаче ей ряда опций и команд с аргументами. Базовый синтаксис имеет такой вид:

docker [option] [command] [arguments]

Чтобы просмотреть все подкоманды, введите:

В Docker 1.11.1 полный список доступных подкоманд выглядит так:

attach Attach to a running container
build Build an image from a Dockerfile
commit Create a new image from a container’s changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes on a container’s filesystem
events Get real time events from the server
exec Run a command in a running container
export Export a container’s filesystem as a tar archive
history Show the history of an image
images List images
import Import the contents from a tarball to create a filesystem image
info Display system-wide information
inspect Return low-level information on a container or image
kill Kill a running container
load Load an image from a tar archive or STDIN
login Log in to a Docker registry
logout Log out from a Docker registry
logs Fetch the logs of a container
network Manage Docker networks
pause Pause all processes within a container
port List port mappings or a specific mapping for the CONTAINER
ps List containers
pull Pull an image or a repository from a registry
push Push an image or a repository to a registry
rename Rename a container
restart Restart a container
rm Remove one or more containers
rmi Remove one or more images
run Run a command in a new container
save Save one or more images to a tar archive
search Search the Docker Hub for images
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop a running container
tag Tag an image into a repository
top Display the running processes of a container
unpause Unpause all processes within a container
update Update configuration of one or more containers
version Show the Docker version information
volume Manage Docker volumes
wait Block until a container stops, then print its exit code

Читайте также:  Fire doors with windows

Чтобы получить общесистемную информацию о Docker, введите:

4: Образы Docker

Контейнеры Docker запускаются из образов. По умолчанию образы Docker хранятся на Docker Hub – это каталог Docker, поддерживаемый командой разработчиков проекта. Разместить свой образ Docker на Docker Hub может любой пользователь, потому здесь можно найти образы для большей части приложений и дистрибутивов Linux.

Чтобы проверить доступ и возможность загружать образы с Docker Hub, введите:

docker run hello-world

Команда должна вернуть следующий результат:

Hello from Docker.
This message shows that your installation appears to be working correctly.
.

Для поиска необходимых образов на Docker Hub используется команда docker и подкоманда search. К примеру, чтобы найти образ CentOS, нужно ввести:

docker search centos

Данная команда выполнит поиск по Docker Hub и вернёт список образов, чьё имя соответствует поисковому запросу. В данном случае команда вернула:

NAME DESCRIPTION STARS OFFICIAL AUTOMATED
centos The official build of CentOS. 2224 [OK] jdeathe/centos-ssh CentOS-6 6.7 x86_64 / CentOS-7 7.2.1511 x8. 22 [OK] jdeathe/centos-ssh-apache-php CentOS-6 6.7 x86_64 / Apache / PHP / PHP M. 17 [OK] million12/centos-supervisor Base CentOS-7 with supervisord launcher, h. 11 [OK] nimmis/java-centos This is docker images of CentOS 7 with dif. 10 [OK] torusware/speedus-centos Always updated official CentOS docker imag. 8 [OK] nickistre/centos-lamp LAMP on centos setup 3 [OK] .

Если в столбце OFFICIAL содержится OK, это значит, что данный образ поддерживается командой разработчиков проекта. Выбрав необходимый образ, вы можете загрузить его при помощи подкоманды pull:

docker pull centos

Загрузив образ, вы можете запустить контейнер с помощью подкоманды run. Если команда docker run обнаружит, что запрашиваемый образ не был загружен, она выполнит его загрузку самостоятельно, а затем запустит контейнер.

docker run centos

Чтобы просмотреть список загруженных образов, введите:

docker images
[secondary_lable Output] REPOSITORY TAG IMAGE ID CREATED SIZE
centos latest 778a53015523 5 weeks ago 196.7 MB
hello-world latest 94df4f0ce8a4 2 weeks ago 967 B

Далее в руководстве будет показано, как изменять загруженные образы и использовать их для создания новых образов, которые затем можно загрузить на Docker Hub или в другой каталог Docker.

5: Запуск контейнера Docker

Ранее загруженный контейнер hello-world – это всего лишь образец контейнера. Существует множество полезны контейнеров. Кроме того, они бывают интерактивными. В целом они очень похожи на ресурсосберегающие виртуальные машины.

Для примера попробуйте запустить контейнер при помощи последнего образа CentOS. Комбинация опций –i и –t откроет интерактивную оболочку контейнера:

docker run -it centos

Командная строка должна измениться, что указывает на то, что теперь вы работаете в контейнере:

Примечание: В командной строке будет указан id контейнера (в данном примере это d9b100f2f636). Запишите его – он необходим для дальнейшей работы.

Внутри контейнера можно запускать любые команды. Попробуйте установить в контейнер какое-нибудь приложение, например, MariaDB. Имейте в виду: теперь добавлять префикс sudo не нужно, поскольку работа внутри контейнера выполняется с правами root.

yum install mariadb-server

6: Коммиты контейнеров Docker

Файловые системы Docker являются временными по умолчанию. После запуска образа Docker вы можете создавать, изменять и удалять файлы так же, как на виртуальной машине. Однако если вы остановите контейнер, а позже запустите его снова, все изменения будут потеряны: все ранее удалённые файлы будут восстановлены, а все новые файлы или внесенные изменения будут утрачены. Это потому, что образы Docker больше похожи на шаблоны, чем на стандартные образы.

Чтобы сохранить все изменения внутри контейнера (и иметь к ним доступ даже после его перезапуска), используйте тома данных Docker.

Данный раздел научит вас сохранять состояние контейнера в качестве нового образа Docker.

Итак, в контейнер CentOS вы установили приложение MariaDB. Теперь контейнер отличается от образа, который был использован для его создания.

Чтобы сохранить текущее состояние контейнера в качестве нового образа, сначала закройте контейнер:

Затем передайте все изменения в новый образ Docker при помощи следующей команды. Опция –m позволяет создать сообщение о коммите, которое предоставит вам (и другим пользователям) подробную информацию о внесённых изменениях. Опция –a позволяет указать автора коммита. ID контейнера был выписан из командной строки. В качестве репозитория, как правило, указывается имя пользователя your Docker Hub:

docker commit -m «What did you do to the image» -a «Author Name» container-id repository/new_image_name

docker commit -m «added mariadb-server» -a «Sunday Ogwu-Chinuwa» 59839a1b7de2 finid/centos-mariadb

Примечание: Новый образ сначала сохраняется локально. Далее будет показано, как выгрузить новый образ на Docker Hub.

Запросите список доступных образов, чтобы убедиться, что новый образ был сохранён успешно:

Команда вернёт список:

REPOSITORY TAG IMAGE ID CREATED SIZE
finid/centos-mariadb latest 23390430ec73 6 seconds ago 424.6 MB
centos latest 778a53015523 5 weeks ago 196.7 MB
hello-world latest 94df4f0ce8a4 2 weeks ago 967 B

Теперь в списке появился новый образ centos-mariadb, который был получен из существующего образа CentOS, загруженного с Docker Hub. Разница в размерах отражает внесенные изменения (в данном случае установку приложения MariaDB). Поэтому если в дальнейшем вам понадобится контейнер CentOS с предустановленным приложением MariaDB, вы можете просто использовать этот образ. Также можно собирать образы из так называемых Dockerfile, но это очень сложный процесс, который выходит за рамки данного руководства.

7: Список контейнеров Docker

Со временем в вашей системе соберётся определённое количество активных и неактивных контейнеров. Чтобы просмотреть список активных контейнеров, введите:

Читайте также:  Превышен таймаут семафора windows

Команда вернёт такой вывод:

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f7c79cc556dd centos “/bin/bash” 3 hours ago Up 3 hours silly_spence

Чтобы просмотреть список всех контейнеров, добавьте опцию -a:

Чтобы получить список недавно созданных контейнеров, добавьте опцию –l:

Чтобы остановить активный контейнер, введите:

docker stop container-id

Чтобы узнать id контейнера, используйте команду docker ps.

8: Загрузка образов Docker в репозиторий

Создав новый образ Docker, вы можете поделиться им на Docker Hub или в другом каталоге Docker. Для этого нужно иметь аккаунт.

Данный раздел научит вас загружать образы Docker на Docker Hub.

Зарегистрируйтесь на Docker Hub. После этого нужно открыть аккаунт при помощи своих учётных данных.

docker login -u docker-registry-username

Получив доступ к Docker Hub, можно загрузить новый образ:

docker push docker-registry-username/docker-image-name

На выполнение команды уйдёт некоторое время. Команда вернёт:

The push refers to a repository [docker.io/finid/centos-mariadb] 670194edfaf5: Pushed
5f70bf18a086: Mounted from library/centos
6a6c96337be1: Mounted from library/centos
.

Загрузив образ в каталог, вы увидите его в панели инструментов аккаунта.

Если в процессе загрузки произошла ошибка, команда выдаст сообщение:

The push refers to a repository [docker.io/finid/centos-mariadb] e3fbbfb44187: Preparing
5f70bf18a086: Preparing
a3b5c80a4eba: Preparing
7f18b442972b: Preparing
3ce512daaf78: Preparing
7aae4540b42d: Waiting
unauthorized: authentication required

Скорее всего, вам не удалось пройти аутентификацию. Войдите и попробуйте снова отправить образ.

Заключение

Данное руководство охватывает лишь малую часть функций Docker, однако этого должно хватить для начала. Больше статей о работе с Docker можно найти в специальном разделе нашего Информатория.

Как большинство проектов с открытым исходным кодом, программа Docker основана на быстро развивающейся кодовой базе, поэтому рекомендуется часто посещать блог проекта.

Install Docker Engine on CentOS

Estimated reading time: 10 minutes

To get started with Docker Engine on CentOS, make sure you meet the prerequisites, then install Docker.

Prerequisites

OS requirements

To install Docker Engine, you need a maintained version of CentOS 7 or 8. Archived versions aren’t supported or tested.

The centos-extras repository must be enabled. This repository is enabled by default, but if you have disabled it, you need to re-enable it.

The overlay2 storage driver is recommended.

Uninstall old versions

Older versions of Docker were called docker or docker-engine . If these are installed, uninstall them, along with associated dependencies.

It’s OK if yum reports that none of these packages are installed.

The contents of /var/lib/docker/ , including images, containers, volumes, and networks, are preserved. The Docker Engine package is now called docker-ce .

Installation methods

You can install Docker Engine in different ways, depending on your needs:

Most users set up Docker’s repositories and install from them, for ease of installation and upgrade tasks. This is the recommended approach.

Some users download the RPM package and install it manually and manage upgrades completely manually. This is useful in situations such as installing Docker on air-gapped systems with no access to the internet.

In testing and development environments, some users choose to use automated convenience scripts to install Docker.

Install using the repository

Before you install Docker Engine for the first time on a new host machine, you need to set up the Docker repository. Afterward, you can install and update Docker from the repository.

Set up the repository

Install the yum-utils package (which provides the yum-config-manager utility) and set up the stable repository.

Optional: Enable the nightly or test repositories.

These repositories are included in the docker.repo file above but are disabled by default. You can enable them alongside the stable repository. The following command enables the nightly repository.

To enable the test channel, run the following command:

You can disable the nightly or test repository by running the yum-config-manager command with the —disable flag. To re-enable it, use the —enable flag. The following command disables the nightly repository.

Install Docker Engine

Install the latest version of Docker Engine and containerd, or go to the next step to install a specific version:

If prompted to accept the GPG key, verify that the fingerprint matches 060A 61C5 1B55 8A7F 742B 77AA C52F EB6B 621E 9F35 , and if so, accept it.

Got multiple Docker repositories?

If you have multiple Docker repositories enabled, installing or updating without specifying a version in the yum install or yum update command always installs the highest possible version, which may not be appropriate for your stability needs.

Docker is installed but not started. The docker group is created, but no users are added to the group.

To install a specific version of Docker Engine, list the available versions in the repo, then select and install:

a. List and sort the versions available in your repo. This example sorts results by version number, highest to lowest, and is truncated:

The list returned depends on which repositories are enabled, and is specific to your version of CentOS (indicated by the .el7 suffix in this example).

b. Install a specific version by its fully qualified package name, which is the package name ( docker-ce ) plus the version string (2nd column) starting at the first colon ( : ), up to the first hyphen, separated by a hyphen ( — ). For example, docker-ce-18.09.1 .

Читайте также:  Протокол управления ppp связью был прерван windows 10 keenetic

Docker is installed but not started. The docker group is created, but no users are added to the group.

Verify that Docker Engine is installed correctly by running the hello-world image.

This command downloads a test image and runs it in a container. When the container runs, it prints an informational message and exits.

Docker Engine is installed and running. You need to use sudo to run Docker commands. Continue to Linux postinstall to allow non-privileged users to run Docker commands and for other optional configuration steps.

Upgrade Docker Engine

To upgrade Docker Engine, follow the installation instructions, choosing the new version you want to install.

Install from a package

If you cannot use Docker’s repository to install Docker, you can download the .rpm file for your release and install it manually. You need to download a new file each time you want to upgrade Docker Engine.

Go to https://download.docker.com/linux/centos/ and choose your version of CentOS. Then browse to x86_64/stable/Packages/ and download the .rpm file for the Docker version you want to install.

Note: To install a nightly or test (pre-release) package, change the word stable in the above URL to nightly or test . Learn about nightly and test channels.

Install Docker Engine, changing the path below to the path where you downloaded the Docker package.

Docker is installed but not started. The docker group is created, but no users are added to the group.

Verify that Docker Engine is installed correctly by running the hello-world image.

This command downloads a test image and runs it in a container. When the container runs, it prints an informational message and exits.

Docker Engine is installed and running. You need to use sudo to run Docker commands. Continue to Post-installation steps for Linux to allow non-privileged users to run Docker commands and for other optional configuration steps.

Upgrade Docker Engine

To upgrade Docker Engine, download the newer package file and repeat the installation procedure, using yum -y upgrade instead of yum -y install , and pointing to the new file.

Install using the convenience script

Docker provides convenience scripts at get.docker.com and test.docker.com for installing edge and testing versions of Docker Engine — Community into development environments quickly and non-interactively. The source code for the scripts is in the docker-install repository. Using these scripts is not recommended for production environments, and you should understand the potential risks before you use them:

  • The scripts require root or sudo privileges to run. Therefore, you should carefully examine and audit the scripts before running them.
  • The scripts attempt to detect your Linux distribution and version and configure your package management system for you. In addition, the scripts do not allow you to customize any installation parameters. This may lead to an unsupported configuration, either from Docker’s point of view or from your own organization’s guidelines and standards.
  • The scripts install all dependencies and recommendations of the package manager without asking for confirmation. This may install a large number of packages, depending on the current configuration of your host machine.
  • The script does not provide options to specify which version of Docker to install, and installs the latest version that is released in the “edge” channel.
  • Do not use the convenience script if Docker has already been installed on the host machine using another mechanism.

This example uses the script at get.docker.com to install the latest release of Docker Engine — Community on Linux. To install the latest testing version, use test.docker.com instead. In each of the commands below, replace each occurrence of get with test .

Always examine scripts downloaded from the internet before running them locally.

If you would like to use Docker as a non-root user, you should now consider adding your user to the “docker” group with something like:

Remember to log out and back in for this to take effect!

Adding a user to the “docker” group grants them the ability to run containers which can be used to obtain root privileges on the Docker host. Refer to Docker Daemon Attack Surface for more information.

Docker Engine — Community is installed. It starts automatically on DEB -based distributions. On RPM -based distributions, you need to start it manually using the appropriate systemctl or service command. As the message indicates, non-root users can’t run Docker commands by default.

Upgrade Docker after using the convenience script

If you installed Docker using the convenience script, you should upgrade Docker using your package manager directly. There is no advantage to re-running the convenience script, and it can cause issues if it attempts to re-add repositories which have already been added to the host machine.

Uninstall Docker Engine

Uninstall the Docker Engine, CLI, and Containerd packages:

Images, containers, volumes, or customized configuration files on your host are not automatically removed. To delete all images, containers, and volumes:

You must delete any edited configuration files manually.

Оцените статью