How to install docker to ubuntu

How to install docker to ubuntu

How To Install and Use Docker on Ubuntu 20.04

Home » SysAdmin » How To Install and Use Docker on Ubuntu 20.04

Docker is a set of platform-as-a-service products used to launch and manage containers. Developers use Docker containers for developing and deploying applications because they provide isolated, lightweight, virtual environments.

In this tutorial, learn how to install Docker on Ubuntu 20.04. We also cover basic commands to get you started.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Install Docker on Ubuntu 20.04

There are two options when for installing Docker on your Ubuntu system:

When you download a package from the default Ubuntu repository, it may not be the latest version. If installing the latest (or a specific) version of Docker is important, use the official repository.

Option 1: Installing Docker from Official Repository

Step 1: Updating the Software Repository

Start by opening a terminal window and updating the local repository:

Wait for the process to complete.

Step 2: Downloading Dependencies

Allow your Ubuntu 20.04 system to access the Docker repositories over HTTPS by running:

The above-mentioned command:

Step 3: Adding Docker’s GPG Key

Next, add the GPG key to ensure the authenticity of the software package:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Step 4: Installing the Docker Repository

Now install the Docker repository using the command:

The command installs the latest repository for your specific Ubuntu release (in this case, 20.04 Focal Fossa).

Step 5: Installing the Latest Docker

Start by updating the repository again:

Now you can install the latest Docker version with:

Step 6: Verifying Docker Installation

To confirm the installation check the version of Docker:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

It should show the Docker version, as in the image above.

Step 7: Enable Docker Service

To start the Docker service run the following commands:

Enable Docker to run at startup with:

To check the status of the service, use the command:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Option 2: Installing Docker from Default Repositories

Step 1: Updating the Local Repository

Open a terminal window and update the local repository with:

Step 2: Uninstalling Old Docker Versions

Before installing the software, make sure you remove any old Docker packages on your Ubuntu 20.04 by running the command:

Step 3: Installing Docker

Now let’s install Docker on Ubuntu 20.04. Run the following command in the terminal window:

Type y and hit Enter to confirm the installation. Once the install is completed, the output notifies you Docker has been installed.

Step 4: Checking Docker Installation

To verify the installation check the Docker version:

The output displays the Docker version, as in the image below.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Step 5: Starting Docker Service

Start the Docker service by running:

Then, enable it to run at startup:

To check the status of the service, run:

The output should verify Docker is active (running ).

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Use Docker on Ubuntu 20.04

The basic syntax for docker commands is:

Run Docker Commands Without Sudo

By default, you can only use the docker commands with root privileges. Ubuntu requires the use of the sudo prefix. For example, if you try to run a hello-world container, the output displays permission was denied.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

It is advisable to keep the settings as is. However, you can bypass typing sudo every time. Adding the user to the docker group grants privileges equivalent to root.

1. First, create the docker group with the command:

2. Then, type the following command (making sure to replace [user] with your username):

3. Enable the new settings with:

4. Lastly, check to confirm the user is now a part of the docker group by running:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

5. Now you can run the docker run hello-world command without the sudo prefix.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Working With Docker Images

Docker images are files that contain the source code, libraries, dependencies, tools, and other files a container needs. You can create Docker images with Dockerfiles or use existing ones available on Docker Hub.

To download a new Docker image, use the command:

If you don’t know the exact name of the image, search for it in Docker’s repository with:

After working with Docker for some time, you will collect a local registry of images. Display a list of all Docker images on the system with:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Note: To learn more about managing images, refer to a detailed list of Docker image commands.

Working With Docker Containers

Docker containers are isolated virtual environments that run based on the Docker image assigned to them.

To run a container based on an existing Docker image, use the command:

Using the command above runs a container but doesn’t move you inside of it. To run a container in interactive mode and change to the container command prompt, run:

Note: Learn how to run a container in How to Use Docker Run Command With Examples.

Another useful docker command is listing all the containers on the system. To list all active containers, type:

To view all containers (active and inactive), run:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Note: Check out more container practices in How to Manage Docker Containers.

Working With Docker Volumes

The best way to preserve data generated within a container is mounting Docker volumes on to them. Mounted volumes don’t depend on the container life cycle and can share data between containers.

Create a new Docker volume with:

To create a container and mount a volume to it, follow the syntax:

For more information about Docker volumes and how to share between containers, refer to Docker Volumes: How To Create & Get Started.

This article should have helped you install and get started with Docker on Ubuntu 20.04.

Be sure to read our other Docker tutorials.

Установка Docker на Ubuntu

Docker не реализует собственную систему контейнеров, он использует LXC и выступает в качестве оболочки, которая позволяет автоматически загружать, устанавливать и запускать образы контейнеров, а также управлять ими. Все действия выполняются в несколько команд и намного проще чем при использовании lxc. В этой статье мы рассмотрим как выполняется установка docker на Ubuntu, а также как использовать контейнеры в Linux.

Системные требования

Для работы docker ваша система должна отвечать таким требованиям:

Если вы используете Ubuntu версии выше 16.04, то проблем с ядром не возникнет, так как эта система поставляется с ядром 4.2 по умолчанию.

Установка Docker в Ubuntu

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

sudo apt update && sudo apt upgrade

Перед тем как установить Docker Ubuntu необходимо установить дополнительные пакеты ядра, которые позволяют использовать Aufs для контейнеров Docker. С помощью этой файловой системы мы сможем следить за изменениями и делать мгновенные снимки контейнеров:

Ещё надо установить пакеты, необходимые для работы apt по https:

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

После того как все приготовления завершены и вы убедились что ваша система полностью готова, можно перейти к установке. Мы будем устанавливать программу из официального репозитория разработчиков. Сначала надо добавить ключ репозитория:

Затем добавьте репозиторий docker в систему:

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

sudo apt update && apt-cache policy docker-ce

И установка Docker на Ubuntu:

Чтобы завершить установку осталось добавить нашего пользователя в группу docker. Иначе при запуске утилиты вы будете получать ошибку подключения к сокету:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Для добавления выполните:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Затем проверяем запущен ли сервис:

sudo systemctl status docker

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Все готово к работе. Теперь рассмотрим подробнее использование Docker.

Установка Docker Compose

Сейчас работа с docker не обходится без утилиты управления контейнерами docker compose, давайте её тоже установим. Чтобы установить docker compose Ubuntu выполните последовательность команд:

sudo chmod +x /usr/local/bin/docker-compose

Утилита была загружена из официального сайта и теперь вы можете посмотреть её версию:

Утилита Docker

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

$ docker опции команда опции_команды аргументы

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Давайте сначала рассмотрим основные опции утилиты их всего несколько:

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

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

Теперь, когда мы рассмотрели все основы, приведем несколько примеров работы с контейнерами. Это очень просто.

Использование Docker в Ubuntu

Чтобы убедиться что все работает давайте запустим тестовый образ. Для этого наберите:

docker run hello-world

Больше ничего не нужно, программа сама скачает образ, и выполнит оболочку в нем. Вы увидите сообщение Hello from Docker:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Поиск и установка контейнеров

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

docker search ubuntu

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Для загрузки образа на локальный компьютер используйте команду pull:

docker pull ubuntu

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

После завершения загрузки вы можете посмотреть список установленных образов:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

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

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

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

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Например, установим утилиту dialog:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Сохранение изменений

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

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Отсюда возьмите id контейнера, затем выполните такую команду для создания нового образа:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Новый образ был сохранен на вашем компьютере и вы можете увидеть его в списке образов:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

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

Как я уже говорил, вы можете посмотреть список запущенных контейнеров с помощью команды ps:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

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

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

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

Чтобы остановить запущенный контейнер используйте команду stop:

docker stop d034b794a3bf

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

docker start d034b794a3bf

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Вы можете подключиться к запущенному контейнеру с помощью attach:

docker attach d034b794a3bf

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

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

docker rm d034b794a3bf

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Выводы

Вы этой статье мы рассмотрели как выполняется установка Docker Ubuntu. В этом дистрибутиве процесс установки не будет трудным даже для новичков. А возможность установки различных дистрибутивов в несколько команд может быть полезной во многих ситуациях. А вы пользуетесь Docker? Для решения каких задач? Напишите в комментариях!

How To Install and Use Docker on Ubuntu 18.04

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

A previous version of this tutorial was written by finid.

Introduction

Docker is an application that simplifies the process of managing application processes in containers. Containers let you run your applications in resource-isolated processes. They’re similar to virtual machines, but containers are more portable, more resource-friendly, and more dependent on the host operating system.

For a detailed introduction to the different components of a Docker container, check out The Docker Ecosystem: An Introduction to Common Components.

In this tutorial, you’ll install and use Docker Community Edition (CE) on Ubuntu 18.04. You’ll install Docker itself, work with containers and images, and push an image to a Docker Repository.

Prerequisites

To follow this tutorial, you will need the following:

Step 1 — Installing Docker

The Docker installation package available in the official Ubuntu repository may not be the latest version. To ensure we get the latest version, we’ll install Docker from the official Docker repository. To do that, we’ll add a new package source, add the GPG key from Docker to ensure the downloads are valid, and then install the package.

First, update your existing list of packages:

Next, install a few prerequisite packages which let apt use packages over HTTPS:

Then add the GPG key for the official Docker repository to your system:

Add the Docker repository to APT sources:

Next, update the package database with the Docker packages from the newly added repo:

Make sure you are about to install from the Docker repo instead of the default Ubuntu repo:

You’ll see output like this, although the version number for Docker may be different:

Notice that docker-ce is not installed, but the candidate for installation is from the Docker repository for Ubuntu 18.04 ( bionic ).

Finally, install Docker:

Docker should now be installed, the daemon started, and the process enabled to start on boot. Check that it’s running:

The output should be similar to the following, showing that the service is active and running:

Installing Docker now gives you not just the Docker service (daemon) but also the docker command line utility, or the Docker client. We’ll explore how to use the docker command later in this tutorial.

Step 2 — Executing the Docker Command Without Sudo (Optional)

By default, the docker command can only be run the root user or by a user in the docker group, which is automatically created during Docker’s installation process. If you attempt to run the docker command without prefixing it with sudo or without being in the docker group, you’ll get an output like this:

If you want to avoid typing sudo whenever you run the docker command, add your username to the docker group:

To apply the new group membership, log out of the server and back in, or type the following:

You will be prompted to enter your user’s password to continue.

Confirm that your user is now added to the docker group by typing:

If you need to add a user to the docker group that you’re not logged in as, declare that username explicitly using:

Let’s explore the docker command next.

Step 3 — Using the Docker Command

Using docker consists of passing it a chain of options and commands followed by arguments. The syntax takes this form:

To view all available subcommands, type:

As of Docker 20, the complete list of available subcommands includes:

To view the options available to a specific command, type:

To view system-wide information about Docker, use:

Let’s explore some of these commands. We’ll start by working with images.

Step 4 — Working with Docker Images

Docker containers are built from Docker images. By default, Docker pulls these images from Docker Hub, a Docker registry managed by Docker, the company behind the Docker project. Anyone can host their Docker images on Docker Hub, so most applications and Linux distributions you’ll need will have images hosted there.

To check whether you can access and download images from Docker Hub, type:

The output will indicate that Docker in working correctly:

Docker was initially unable to find the hello-world image locally, so it downloaded the image from Docker Hub, which is the default repository. Once the image downloaded, Docker created a container from the image and the application within the container executed, displaying the message.

You can search for images available on Docker Hub by using the docker command with the search subcommand. For example, to search for the Ubuntu image, type:

The script will crawl Docker Hub and return a listing of all images whose name match the search string. In this case, the output will be similar to this:

In the OFFICIAL column, OK indicates an image built and supported by the company behind the project. Once you’ve identified the image that you would like to use, you can download it to your computer using the pull subcommand.

Execute the following command to download the official ubuntu image to your computer:

You’ll see the following output:

After an image has been downloaded, you can then run a container using the downloaded image with the run subcommand. As you saw with the hello-world example, if an image has not been downloaded when docker is executed with the run subcommand, the Docker client will first download the image, then run a container using it.

To see the images that have been downloaded to your computer, type:

The output should look similar to the following:

As you’ll see later in this tutorial, images that you use to run containers can be modified and used to generate new images, which may then be uploaded (pushed is the technical term) to Docker Hub or other Docker registries.

Let’s look at how to run containers in more detail.

Step 5 — Running a Docker Container

The hello-world container you ran in the previous step is an example of a container that runs and exits after emitting a test message. Containers can be much more useful than that, and they can be interactive. After all, they are similar to virtual machines, only more resource-friendly.

As an example, let’s run a container using the latest image of Ubuntu. The combination of the -i and -t switches gives you interactive shell access into the container:

Your command prompt should change to reflect the fact that you’re now working inside the container and should take this form:

Then install any application in it. Let’s install Node.js:

This installs Node.js in the container from the official Ubuntu repository. When the installation finishes, verify that Node.js is installed:

You’ll see the version number displayed in your terminal:

Any changes you make inside the container only apply to that container.

To exit the container, type exit at the prompt.

Let’s look at managing the containers on our system next.

Step 6 — Managing Docker Containers

After using Docker for a while, you’ll have many active (running) and inactive containers on your computer. To view the active ones, use:

You will see output similar to the following:

In this tutorial, you started two containers; one from the hello-world image and another from the ubuntu image. Both containers are no longer running, but they still exist on your system.

You’ll see output similar to this:

The container will start, and you can use docker ps to see its status:

Containers can be turned into images which you can use to build new containers. Let’s look at how that works.

Step 7 — Committing Changes in a Container to a Docker Image

When you start up a Docker image, you can create, modify, and delete files just like you can with a virtual machine. The changes that you make will only apply to that container. You can start and stop it, but once you destroy it with the docker rm command, the changes will be lost for good.

This section shows you how to save the state of a container as a new Docker image.

After installing Node.js inside the Ubuntu container, you now have a container running off an image, but the container is different from the image you used to create it. But you might want to reuse this Node.js container as the basis for new images later.

Then commit the changes to a new Docker image instance using the following command.

The -m switch is for the commit message that helps you and others know what changes you made, while -a is used to specify the author. The container_id is the one you noted earlier in the tutorial when you started the interactive Docker session. Unless you created additional repositories on Docker Hub, the repository is usually your Docker Hub username.

When you commit an image, the new image is saved locally on your computer. Later in this tutorial, you’ll learn how to push an image to a Docker registry like Docker Hub so others can access it.

Listing the Docker images again will show the new image, as well as the old one that it was derived from:

You’ll see output like this:

In this example, ubuntu-nodejs is the new image, which was derived from the existing ubuntu image from Docker Hub. The size difference reflects the changes that were made. And in this example, the change was that NodeJS was installed. So next time you need to run a container using Ubuntu with NodeJS pre-installed, you can just use the new image.

Now let’s share the new image with others so they can create containers from it.

Step 8 — Pushing Docker Images to a Docker Repository

The next logical step after creating a new image from an existing image is to share it with a select few of your friends, the whole world on Docker Hub, or other Docker registry that you have access to. To push an image to Docker Hub or any other Docker registry, you must have an account there.

This section shows you how to push a Docker image to Docker Hub. To learn how to create your own private Docker registry, check out How To Set Up a Private Docker Registry on Ubuntu 14.04.

To push your image, first log into Docker Hub.

You’ll be prompted to authenticate using your Docker Hub password. If you specified the correct password, authentication should succeed.

Note: If your Docker registry username is different from the local username you used to create the image, you will have to tag your image with your registry username. For the example given in the last step, you would type:

Then you may push your own image using:

To push the ubuntu-nodejs image to the sammy repository, the command would be:

The process may take some time to complete as it uploads the images, but when completed, the output will look like this:

After pushing an image to a registry, it should be listed on your account’s dashboard, like that show in the image below.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

If a push attempt results in an error of this sort, then you likely did not log in:

Log in with docker login and repeat the push attempt. Then verify that it exists on your Docker Hub repository page.

You can now use docker pull sammy / ubuntu-nodejs to pull the image to a new machine and use it to run a new container.

Conclusion

In this tutorial you installed Docker, worked with images and containers, and pushed a modified image to Docker Hub. Now that you know the basics, explore the other Docker tutorials in the DigitalOcean Community.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

How To Install and Use Docker on Ubuntu 20.04

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

Introduction

Docker is an application that simplifies the process of managing application processes in containers. Containers let you run your applications in resource-isolated processes. They’re similar to virtual machines, but containers are more portable, more resource-friendly, and more dependent on the host operating system.

For a detailed introduction to the different components of a Docker container, check out The Docker Ecosystem: An Introduction to Common Components.

In this tutorial, you’ll install and use Docker Community Edition (CE) on Ubuntu 20.04. You’ll install Docker itself, work with containers and images, and push an image to a Docker Repository.

Prerequisites

To follow this tutorial, you will need the following:

Step 1 — Installing Docker

The Docker installation package available in the official Ubuntu repository may not be the latest version. To ensure we get the latest version, we’ll install Docker from the official Docker repository. To do that, we’ll add a new package source, add the GPG key from Docker to ensure the downloads are valid, and then install the package.

First, update your existing list of packages:

Next, install a few prerequisite packages which let apt use packages over HTTPS:

Then add the GPG key for the official Docker repository to your system:

Add the Docker repository to APT sources:

This will also update our package database with the Docker packages from the newly added repo.

Make sure you are about to install from the Docker repo instead of the default Ubuntu repo:

You’ll see output like this, although the version number for Docker may be different:

Notice that docker-ce is not installed, but the candidate for installation is from the Docker repository for Ubuntu 20.04 ( focal ).

Finally, install Docker:

Docker should now be installed, the daemon started, and the process enabled to start on boot. Check that it’s running:

The output should be similar to the following, showing that the service is active and running:

Installing Docker now gives you not just the Docker service (daemon) but also the docker command line utility, or the Docker client. We’ll explore how to use the docker command later in this tutorial.

Step 2 — Executing the Docker Command Without Sudo (Optional)

By default, the docker command can only be run the root user or by a user in the docker group, which is automatically created during Docker’s installation process. If you attempt to run the docker command without prefixing it with sudo or without being in the docker group, you’ll get an output like this:

If you want to avoid typing sudo whenever you run the docker command, add your username to the docker group:

To apply the new group membership, log out of the server and back in, or type the following:

You will be prompted to enter your user’s password to continue.

Confirm that your user is now added to the docker group by typing:

If you need to add a user to the docker group that you’re not logged in as, declare that username explicitly using:

Let’s explore the docker command next.

Step 3 — Using the Docker Command

Using docker consists of passing it a chain of options and commands followed by arguments. The syntax takes this form:

To view all available subcommands, type:

As of Docker 19, the complete list of available subcommands includes:

To view the options available to a specific command, type:

To view system-wide information about Docker, use:

Let’s explore some of these commands. We’ll start by working with images.

Step 4 — Working with Docker Images

Docker containers are built from Docker images. By default, Docker pulls these images from Docker Hub, a Docker registry managed by Docker, the company behind the Docker project. Anyone can host their Docker images on Docker Hub, so most applications and Linux distributions you’ll need will have images hosted there.

To check whether you can access and download images from Docker Hub, type:

The output will indicate that Docker in working correctly:

Docker was initially unable to find the hello-world image locally, so it downloaded the image from Docker Hub, which is the default repository. Once the image downloaded, Docker created a container from the image and the application within the container executed, displaying the message.

You can search for images available on Docker Hub by using the docker command with the search subcommand. For example, to search for the Ubuntu image, type:

The script will crawl Docker Hub and return a listing of all images whose name match the search string. In this case, the output will be similar to this:

In the OFFICIAL column, OK indicates an image built and supported by the company behind the project. Once you’ve identified the image that you would like to use, you can download it to your computer using the pull subcommand.

Execute the following command to download the official ubuntu image to your computer:

You’ll see the following output:

After an image has been downloaded, you can then run a container using the downloaded image with the run subcommand. As you saw with the hello-world example, if an image has not been downloaded when docker is executed with the run subcommand, the Docker client will first download the image, then run a container using it.

To see the images that have been downloaded to your computer, type:

The output will look similar to the following:

As you’ll see later in this tutorial, images that you use to run containers can be modified and used to generate new images, which may then be uploaded (pushed is the technical term) to Docker Hub or other Docker registries.

Let’s look at how to run containers in more detail.

Step 5 — Running a Docker Container

The hello-world container you ran in the previous step is an example of a container that runs and exits after emitting a test message. Containers can be much more useful than that, and they can be interactive. After all, they are similar to virtual machines, only more resource-friendly.

As an example, let’s run a container using the latest image of Ubuntu. The combination of the -i and -t switches gives you interactive shell access into the container:

Your command prompt should change to reflect the fact that you’re now working inside the container and should take this form:

Then install any application in it. Let’s install Node.js:

This installs Node.js in the container from the official Ubuntu repository. When the installation finishes, verify that Node.js is installed:

You’ll see the version number displayed in your terminal:

Any changes you make inside the container only apply to that container.

To exit the container, type exit at the prompt.

Let’s look at managing the containers on our system next.

Step 6 — Managing Docker Containers

After using Docker for a while, you’ll have many active (running) and inactive containers on your computer. To view the active ones, use:

You will see output similar to the following:

In this tutorial, you started two containers; one from the hello-world image and another from the ubuntu image. Both containers are no longer running, but they still exist on your system.

You’ll see output similar to this:

The container will start, and you can use docker ps to see its status:

Containers can be turned into images which you can use to build new containers. Let’s look at how that works.

Step 7 — Committing Changes in a Container to a Docker Image

When you start up a Docker image, you can create, modify, and delete files just like you can with a virtual machine. The changes that you make will only apply to that container. You can start and stop it, but once you destroy it with the docker rm command, the changes will be lost for good.

This section shows you how to save the state of a container as a new Docker image.

After installing Node.js inside the Ubuntu container, you now have a container running off an image, but the container is different from the image you used to create it. But you might want to reuse this Node.js container as the basis for new images later.

Then commit the changes to a new Docker image instance using the following command.

The -m switch is for the commit message that helps you and others know what changes you made, while -a is used to specify the author. The container_id is the one you noted earlier in the tutorial when you started the interactive Docker session. Unless you created additional repositories on Docker Hub, the repository is usually your Docker Hub username.

When you commit an image, the new image is saved locally on your computer. Later in this tutorial, you’ll learn how to push an image to a Docker registry like Docker Hub so others can access it.

Listing the Docker images again will show the new image, as well as the old one that it was derived from:

You’ll see output like this:

In this example, ubuntu-nodejs is the new image, which was derived from the existing ubuntu image from Docker Hub. The size difference reflects the changes that were made. And in this example, the change was that NodeJS was installed. So next time you need to run a container using Ubuntu with NodeJS pre-installed, you can just use the new image.

Now let’s share the new image with others so they can create containers from it.

Step 8 — Pushing Docker Images to a Docker Repository

The next logical step after creating a new image from an existing image is to share it with a select few of your friends, the whole world on Docker Hub, or other Docker registry that you have access to. To push an image to Docker Hub or any other Docker registry, you must have an account there.

This section shows you how to push a Docker image to Docker Hub. To learn how to create your own private Docker registry, check out How To Set Up a Private Docker Registry on Ubuntu 18.04.

To push your image, first log into Docker Hub.

You’ll be prompted to authenticate using your Docker Hub password. If you specified the correct password, authentication should succeed.

Note: If your Docker registry username is different from the local username you used to create the image, you will have to tag your image with your registry username. For the example given in the last step, you would type:

Then you may push your own image using:

To push the ubuntu-nodejs image to the sammy repository, the command would be:

The process may take some time to complete as it uploads the images, but when completed, the output will look like this:

After pushing an image to a registry, it should be listed on your account’s dashboard, like that show in the image below.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

If a push attempt results in an error of this sort, then you likely did not log in:

Log in with docker login and repeat the push attempt. Then verify that it exists on your Docker Hub repository page.

You can now use docker pull sammy / ubuntu-nodejs to pull the image to a new machine and use it to run a new container.

Conclusion

In this tutorial you installed Docker, worked with images and containers, and pushed a modified image to Docker Hub. Now that you know the basics, explore the other Docker tutorials in the DigitalOcean Community.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

How to Install and Use Docker on Ubuntu 20.04

Docker is a most popular, open-source platform for developers and system administrators to build, run, and share applications with containers. Containerization (the use of containers to deploy applications) is becoming popular because containers are flexible, lightweight, portable, loosely coupled, scalable, and more secure.

This article is a good starting point for beginners to learn how to install and use Docker on a Ubuntu 20.04 Linux system with some basic commands. For this guide, we will install Docker Community Edition (CE).

Prerequisites:

Installing Docker on Ubuntu 20.04

To use the latest version of Docker, we will install it from the official Docker repository. So, start by adding the GPG key for the official Docker repository to your system, after that add the repository configuration to the APT source with the following commands.

Now update the APT package cache to include the new Docker packages to the system using the following command.

Next, install the Docker package as shown.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Install Docker on Ubuntu

During the Docker package installation process, the package installer triggers the systemd (system and service manager) to automatically start and enable the docker service. Using the following commands to confirm that the docker service is active and is enabled to automatically start at system startup. Also, check its status:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Check Docker Status

There are several other systemctl commands to manage and control the docker service which includes the following:

To check the version of Docker CE installed on your system, run the following command:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Check Docker Version

You can view available docker usage commands by running the docker command without any options or arguments:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu List of Docker Commands

Manage Docker as a non-root User with sudo Command

By default, the Docker daemon binds to a UNIX socket (instead of a TCP port) which is owned by the user root. Therefore the Docker daemon always runs as the root user and to run the docker command, you need to use sudo.

Besides, during the Docker package installation, a group called docker is created. When the Docker daemon starts, it creates a UNIX socket accessible by members of the docker group (which grants privileges equivalent to the root user).

To run the docker command without sudo, add all non-root users who are supposed to access docker, in the docker group as follows. In this example, the command adds the currently logged on user ($USER) or username to the docker group:

To activate the changes to groups, run the following command:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Add User to Docker Group

Next, verify that you can run docker commands without sudo. The following command downloads a test image and runs it in a container. Once the container is running, it prints an informational message and exits. This is also another way to cross-check whether your installation is working fine.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Verify Docker Installation

Working with Docker Images

A Docker image is a read-only template file with instructions for creating a Docker container. You can either create your custom images or you can only use those created by others and published in the Docker Hub, the world’s largest library and community for container images.

You can search for an centos image in the Docker Hub with the following command:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Search Docker Images

To download an image locally, use the pull command. This example shows how to download the official centos image.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Download CentOS Docker Image

Once the download is complete, you can list the available images on your local system.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu List Docker Images

If you no longer need an image, you can remove it from your system.

Running and Managing Docker Containers

A Docker container is a process that runs natively on Linux and shares the kernel of the host machine with other containers. Concerning a Docker image, a container is just a running image.

To start a container based on your new centos image, run the following command where “centos” is the local image name and “cat /etc/centos-release” is the command to run in the container:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Run Commands in Docker Container

A container runs a discrete process that is isolated in that it has its own: file system, networking, and isolated process tree separate from the host. Note that you can manipulate a container using the container’s ID, ID-prefix, or name as shown below. The above container process exits after the command runs.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu List Docker Containers

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Show All Docker Containers

You can also start a container using its container ID after it has exited. For example, in the previous command, our container ID is 94c35e616b91. We can start the container as shown (note that it will run the command and exit):

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Start a Docker Container Using ID

To stop a running container using its ID, use the stop command as shown.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Assign a Name to Docker Container

Now you can use the container name to manage (start, stop, stats, remove, etc.) the container:

Running an Interactive Session into a Docker Container

To launch an interactive shell session in a container to enable you run commands within the container, run the following command:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Start Interactive Shell into a Container

You can exit by issuing the exit command as shown.

If you prefer not to exit, you can detach from a container and leave it running. To do that, use the CTRL+p then CTRL+q key sequence.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Detach Docker from a Running Session

You can connect back to the container using the attach command which will attach local standard input, output, and error streams to the running container:

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu Start Docker Container in Detached Mode

Last but not least, you can stop a running container from the host session by running the following command:

That’s all! In this guide, we have covered how to install and use Docker CE in Ubuntu 20.04 Linux. If you have any questions, use the feedback form below to ask us.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

How to install docker to ubuntu. Смотреть фото How to install docker to ubuntu. Смотреть картинку How to install docker to ubuntu. Картинка про How to install docker to ubuntu. Фото How to install docker to ubuntu

We are thankful for your never ending support.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *