Curl fssl https download docker com linux ubuntu gpg sudo apt key add

Установка Docker и Docker-compose на Ubuntu 20.04

Все еще нет смысла рассказывать, что такое Docker раз вы читаете это. В этом посте я расскажу как быстро и просто установить Docker и Docker-compose на Ubuntu 20.04.

Установка Docker

В репозитории Ubuntu может быть не самая последняя версия Docker. По этому мы будем устанавливать его из официального репозитория Docker.

Сначала обновите существующий список пакетов:

Затем установите несколько обязательных пакетов, которые позволяют apt использовать пакеты по HTTPS:

Добавляем ключ GPG официального репозитория Docker в вашу систему:

Добавляем репозиторий Docker:

Обновляем список пакетов:

Теперь надо убедится, что все нормально и установка будет из репозитория Docker, а не Ubuntu:

На выходе видим плюс минус такую картину:

Если все так, то прекрасно! Установится откуда надо и все будет хорошо.

Ну и финальный штрих, установим Docker:

Проверяем работает ли Docker

Для начала узнаел, что там с Docker’ом:

Отлично! Все завелось и прекрасно работает. Давайте попробуем запустить какой нибудь контейнер:

Если все хорошо, то на выходе увидим:

Разрешаем не root пользователю запускать Docker

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

Добавляем своего пользователя в группу docker :

Перелогиваемся и смело выполняем:

Устанавливаем Docker-compose

Запускаем эту команду для установки последней версии docker-compose, проверить какая версия является последней можно тут:

Делаем файл запускаемым:

При желании можно настроить автодополнение команды для bash или zsh .

Проверяем, как все работает:

Увидим плюс минус:

Собственно все. Удачи!

Чуть не забыл. Вы можете почитать меня в твиттере или телеграме, посмотреть мои фотографии в инстаграме, подружиться со мной в PSN, позлить меня на твиче пока я играю или посмотреть в записи. А самые лучшие человеки могут меня поддержать деньгой.

Источник

Install Docker Engine on Ubuntu

Estimated reading time: 12 minutes

Docker Desktop for Linux

Docker Desktop helps you build, share, and run containers easily on Mac and Windows as you do on Linux. Docker handles the complex setup and allows you to focus on writing the code. Thanks to the positive support we received on the subscription updates, we’ve started working on Docker Desktop for Linux which is the second-most popular feature request in our public roadmap. If you are interested in early access, sign up for our Developer Preview program.

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

Prerequisites

OS requirements

To install Docker Engine, you need the 64-bit version of one of these Ubuntu versions:

  • Ubuntu Hirsute 21.04
  • Ubuntu Focal 20.04 (LTS)
  • Ubuntu Bionic 18.04 (LTS)

Docker Engine is supported on x86_64 (or amd64 ), armhf , arm64 , and s390x architectures.

Ubuntu 16.04 LTS “Xenial Xerus” end-of-life

Ubuntu Linux 16.04 LTS reached the end of its five-year LTS window on April 30th 2021 and is no longer supported. Docker no longer releases packages for this distribution (including patch- and security releases). Users running Docker on Ubuntu 16.04 are recommended to update their system to a currently supported LTS version of Ubuntu.

Uninstall old versions

Older versions of Docker were called docker , docker.io , or docker-engine . If these are installed, uninstall them:

It’s OK if apt-get reports that none of these packages are installed.

The contents of /var/lib/docker/ , including images, containers, volumes, and networks, are preserved. If you do not need to save your existing data, and want to start with a clean installation, refer to the uninstall Docker Engine section at the bottom of this page.

Supported storage drivers

Docker Engine on Ubuntu supports overlay2 , aufs and btrfs storage drivers.

Docker Engine uses the overlay2 storage driver by default. If you need to use aufs instead, you need to configure it manually. See use the AUFS storage driver

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 DEB 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

Update the apt package index and install packages to allow apt to use a repository over HTTPS:

Add Docker’s official GPG key:

Use the following command to set up the stable repository. To add the nightly or test repository, add the word nightly or test (or both) after the word stable in the commands below. Learn about nightly and test channels.

Note: The lsb_release -cs sub-command below returns the name of your Ubuntu distribution, such as xenial . Sometimes, in a distribution like Linux Mint, you might need to change $(lsb_release -cs) to your parent Ubuntu distribution. For example, if you are using Linux Mint Tessa , you could use bionic . Docker does not offer any guarantees on untested and unsupported Ubuntu distributions.

Install Docker Engine

Update the apt package index, and install the latest version of Docker Engine and containerd, or go to the next step to install a specific version:

Got multiple Docker repositories?

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

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

a. List the versions available in your repo:

b. Install a specific version using the version string from the second column, for example, 5:18.09.1

Читайте также:  Где расположен кэш windows

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 a message and exits.

Docker Engine is installed and running. The docker group is created but no users are added to it. 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, first run sudo apt-get update , then 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 Engine, you can download the .deb file for your release and install it manually. You need to download a new file each time you want to upgrade Docker.

Go to https://download.docker.com/linux/ubuntu/dists/ , choose your Ubuntu version, then browse to pool/stable/ , choose amd64 , armhf , arm64 , or s390x , and download the .deb file for the Docker Engine version you want to install.

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.

The Docker daemon starts automatically.

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 a message and exits.

Docker Engine is installed and running. The docker group is created but no users are added to it. 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, pointing to the new file.

Install using the convenience script

Docker provides a convenience script at get.docker.com to install Docker into development environments quickly and non-interactively. The convenience script is not recommended for production environments, but can be used as an example to create a provisioning script that is tailored to your needs. Also refer to the install using the repository steps to learn about installation steps to install using the package repository. The source code for the script is open source, and can be found in the docker-install repository on GitHub.

Always examine scripts downloaded from the internet before running them locally. Before installing, make yourself familiar with potential risks and limitations of the convenience script:

  • The script requires root or sudo privileges to run.
  • The script attempts to detect your Linux distribution and version and configure your package management system for you, and does not allow you to customize most installation parameters.
  • The script installs dependencies and recommendations without asking for confirmation. This may install a large number of packages, depending on the current configuration of your host machine.
  • By default, the script installs the latest stable release of Docker, containerd, and runc. When using this script to provision a machine, this may result in unexpected major version upgrades of Docker. Always test (major) upgrades in a test environment before deploying to your production systems.
  • The script is not designed to upgrade an existing Docker installation. When using the script to update an existing installation, dependencies may not be updated to the expected version, causing outdated versions to be used.

Tip: preview script steps before running

You can run the script with the DRY_RUN=1 option to learn what steps the script will execute during installation:

This example downloads the script from get.docker.com and runs it to install the latest stable release of Docker on Linux:

Docker is installed. The docker service starts automatically on Debian based distributions. On RPM based distributions, such as CentOS, Fedora, RHEL or SLES, you need to start it manually using the appropriate systemctl or service command. As the message indicates, non-root users cannot run Docker commands by default.

Use Docker as a non-privileged user, or install in rootless mode?

The installation script requires root or sudo privileges to install and use Docker. If you want to grant non-root users access to Docker, refer to the post-installation steps for Linux. Docker can also be installed without root privileges, or configured to run in rootless mode. For instructions on running Docker in rootless mode, refer to run the Docker daemon as a non-root user (rootless mode).

Install pre-releases

Docker also provides a convenience script at test.docker.com to install pre-releases of Docker on Linux. This script is equivalent to the script at get.docker.com , but configures your package manager to enable the “test” channel from our package repository, which includes both stable and pre-releases (beta versions, release-candidates) of Docker. Use this script to get early access to new releases, and to evaluate them in a testing environment before they are released as stable.

To install the latest version of Docker on Linux from the “test” channel, run:

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.

Источник

Установка и использование Docker в Ubuntu 20.04

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

Читайте также:

Данный мануал поможет установить и подготовить к работе Docker Community Edition (CE) в Ubuntu 20.04. Вы научитесь не только устанавливать платформу, но и работать с контейнерами и образами.

Требования

  • Сервер Ubuntu 20.04, настроенный согласно этому мануалу.
  • Аккаунт на Docker Hub (если вы хотите создавать и распространять свои собственные образы, как описано в разделе 7 и 8 данного руководства).

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

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

Читайте также:  Описание файловой системы для linux

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

sudo apt update

Установите несколько зависимостей:

sudo apt install apt-transport-https ca-certificates curl software-properties-common

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

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add —

Добавьте репозиторий Docker в APT:

sudo add-apt-repository «deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable»

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

sudo apt update

Следующая команда позволяет переключиться из стандартного репозитория Ubuntu в репозиторий Docker:

apt-cache policy docker-ce

Команда должна вернуть:

docker-ce:
Installed: (none)
Candidate: 5:19.03.9

ubuntu-focal
Version table:
5:19.03.9

ubuntu-focal 500
500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages

Обратите внимание: пакет docker-ce пока не установлен, он только готов к установке. Чтобы установить пакет, введите:

sudo apt install docker-ce

После этого программа 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 Tue 2020-05-19 17:00:41 UTC; 17s ago
TriggeredBy: ● docker.socket
Docs: https://docs.docker.com
Main PID: 24321 (dockerd)
Tasks: 8
Memory: 46.4M
CGroup: /system.slice/docker.service
└─24321 /usr/bin/dockerd -H fd:// —containerd=/run/containerd/containerd.sock

Теперь в вашей системе работает сервис (или демон) 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 $

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

При этом будет запрошен пароль вашего пользователя.

Убедитесь, что пользователь добавлен в группу:

id -nG
8host sudo docker

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

sudo usermod -aG docker username

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

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

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

docker [option] [command] [arguments]

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

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

attach Attach local standard input, output, and error streams 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 to files or directories 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 Docker objects
kill Kill one or more running containers
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
pause Pause all processes within one or more containers
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 one or more containers
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 (streamed to STDOUT by default)
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 one or more running containers
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
version Show the Docker version information
wait Block until one or more containers stop, then print their exit codes

Чтобы получить список опций конкретной подкоманды, введите:

docker docker-subcommand —help

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

4: Образы Docker

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

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

docker run hello-world

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

Unable to find image ‘hello-world:latest’ locally
latest: Pulling from library/hello-world
0e03bdcc26d7: Pull complete
Digest: sha256:6a65f928fb91fcfbc963f7aa6d57c8eeb426ad9a20c7ee045538ef34847f44f1
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
.

Docker не может локально найти образ hello-world, потому он загружает этот образ с Docker Hub. Затем он создает контейнер на основе этого образа и запускает приложение внутри контейнера, после чего выдает это сообщение.

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

docker search ubuntu

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

NAME DESCRIPTION STARS OFFICIAL AUTOMATED
ubuntu Ubuntu is a Debian-based Linux operating sys… 10908 [OK] dorowu/ubuntu-desktop-lxde-vnc Docker image to provide HTML5 VNC interface … 428 [OK] rastasheep/ubuntu-sshd Dockerized SSH service, built on top of offi… 244 [OK] consol/ubuntu-xfce-vnc Ubuntu container with «headless» VNC session… 218 [OK] ubuntu-upstart Upstart is an event-based replacement for th… 108 [OK] ansible/ubuntu14.04-ansible Ubuntu 14.04 LTS with
.

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

docker pull ubuntu
Using default tag: latest
latest: Pulling from library/ubuntu
d51af753c3d3: Pull complete
fc878cd0a91c: Pull complete
6154df8ff988: Pull complete
fee5db0ff82f: Pull complete
Digest: sha256:747d2dbbaaee995098c9792d99bd333c6783ce56150d1b11e333bbceed5c54d7
Status: Downloaded newer image for ubuntu:latest
docker.io/library/ubuntu:latest

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

Читайте также:  Radeon rx 570 4gb драйвер для windows 10

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

docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu latest 1d622ef86b13 3 weeks ago 73.9MB
hello-world latest bf756fb1ae65 4 months ago 13.3kB

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

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

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

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

docker run -it ubuntu

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

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

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

Теперь попробуйте установить в контейнер какое-нибудь приложение, например, NodeJS:

apt install nodejs

Это установит Node.js из официального репозитория Ubuntu. Чтобы проверить установку, введите:

Команда должна вернуть версию пакета:

Любые изменения, внесенные в контейнер, касаются только этого контейнера и никак не влияют на остальную систему.

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

6: Управление контейнерами Docker

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

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

CONTAINER ID IMAGE COMMAND CREATED

В этом примере у нас есть 2 контейнера – hello-world и ubuntu. Оба контейнера сейчас неактивны, потому список пуст.

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

docker ps -a
1c08a7a0d0e4 ubuntu «/bin/bash» 2 minutes ago Exited (0) 8 seconds ago quizzical_mcnulty

a707221a5f6c hello-world «/hello» 6 minutes ago Exited (0) 6 minutes ago youthful_curie

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

docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

1c08a7a0d0e4 ubuntu «/bin/bash» 2 minutes ago Exited (0) 40 seconds ago uizzical_mcnulty

Чтобы запустить неактивный контейнер, введите команду docker start и укажите ID контейнера. Например, чтобы запустить контейнер Ubuntu с ID 1c08a7a0d0e4, нужно ввести:

docker start 1c08a7a0d0e4

Проверьте состояние этого контейнера с помощью команды docker ps:

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

1c08a7a0d0e4 ubuntu «/bin/bash» 3 minutes ago Up 5 seconds quizzical_mcnulty

Чтобы остановить запущенный контейнер, введите docker stop и добавьте ID этого контейнера. Также можно использовать имя, которое контейнерам присваивает Docker. В данном случае это quizzical_mcnulty:

docker stop quizzical_mcnulty

Удалить ненужный контейнер можно с помощью команды docker rm, указав ID или имя контейнера. Чтобы узнать id или имя контейнера, используйте команду docker ps -a. Чтобы удалить контейнер hello-world, нужно ввести:

docker rm youthful_curie

Вы можете запустить новый контейнер и присвоить ему имя с помощью флага –name. Чтобы создать контейнер, который самостоятельно удалится после деактивации, используйте флаг –rm. Больше информации о командах вы найдете в справке:

docker run help

Контейнеры можно превращать в образы, на основе которых вы сможете собирать новые контейнеры.

7: Коммиты контейнеров в образы Docker

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

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

Итак, в контейнер Ubuntu вы установили приложение node.js. Теперь контейнер отличается от исходного образа, который был использован для его создания. Его можно использовать в качестве основы для нового образа.

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

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

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

Например, для пользователя 8host и контейнера с ID d9b100f2f636 команда выглядит так:

docker commit -m «added Node.js» -a «8host» d9b100f2f636 8host/ubuntu-nodejs

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

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

Команда должна вернуть:

REPOSITORY TAG IMAGE ID CREATED SIZE
8host/ubuntu-nodejs latest 7c1f35226ca6 7 seconds ago 179MB
.

В списке появился новый образ ubuntu-nodejs, который был получен из существующего образа ubuntu, загруженного с Docker Hub. Разница в размерах отражает внесенные изменения (в данном случае установку приложения NodeJS). Поэтому если в дальнейшем вам понадобится контейнер Ubuntu с предустановленным приложением Node.JS, вы можете просто использовать этот образ.

Также можно собирать образы из так называемых Dockerfile, но это довольно сложный процесс, который выходит за рамки данного руководства.

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

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

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

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

docker login -u docker-registry-username

Вам будет предложено пройти аутентификацию. Вы сможете войти в свой аккаунт Docker Hub, предоставив правильный пароль.

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

docker tag 8host/ubuntu-nodejs docker-registry-username/ubuntu-nodejs

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

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

Например, для пользователя 8host и образа ubuntu-nodejs команда будет выглядеть так:

docker push 8host/ubuntu-nodejs

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

The push refers to a repository [docker.io/8host/ubuntu-nodejs] e3fbbfb44187: Pushed
5f70bf18a086: Pushed
a3b5c80a4eba: Pushed
7f18b442972b: Pushed
3ce512daaf78: Pushed
7aae4540b42d: Pushed
.

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

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

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

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

Теперь вы можете загрузить свой образ с помощью команды:

docker pull 8host/ubuntu-nodejs

и запустить на его основе новый контейнер.

Заключение

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

Источник

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