Изучаем docker, часть 3: файлы dockerfile

Paso 5: Ejecutar un contenedor de Docker

El contenedor que ejecutó en el paso anterior es un ejemplo de un contenedor que se ejecuta y se cierra tras emitir un mensaje de prueba. Los contenedores pueden ofrecer una utilidad mucho mayor y ser interactivos. Después de todo, son similares a las máquinas virtuales, aunque más flexibles con los recursos.

Como ejemplo, ejecutemos un contenedor usando la imagen más reciente de Ubuntu. La combinación de los conmutadores -i y -t le proporcionan un acceso interactivo del shell al contenedor:

Su símbolo del sistema debe cambiar para reflejar el hecho de que ahora trabaja dentro del contenedor y debe adoptar esta forma:

Tenga en cuenta el ID del contenedor en el símbolo del sistema. En este ejemplo, es . Más adelante, necesitará ese ID de contenedor para identificar el contenedor cuando desee eliminarlo.

Ahora puede ejecutar cualquier comando dentro del contenedor. Por ejemplo, actualicemos la base de datos del paquete dentro del contenedor. No es necesario prefijar ningún comando con , ya que realiza operaciones dentro del contenedor como el usuario root:

Luego, instale cualquier aplicación en él. Probemos con Node.js:

Con esto, se instala Node.js en el contenedor desde el repositorio oficial de Ubuntu. Cuando finalice la instalación, verifique que Node.js esté instalado:

Verá el número de versión en su terminal:

Cualquier cambio que realice dentro del contenedor solo se aplica a este.

Para cerrar el contenedor, escriba a línea de comandos.

A continuación, veremos la forma de administrar los contenedores en nuestro sistema.

#6.Rancher

Rancher is an open-source software platform that enables organizations to run and manage Docker and Kubernetes in production. With Rancher, organizations no longer have to build a container services platform from scratch using a distinct set of open source technologies. Rancher supplies the entire software stack needed to manage containers in production.

Rancher software consists of four major components:

  1. Infrastructure Orchestration
  2. Container Orchestration & Scheduling
  3. Application Catalog
  4. Enterprise-Grade control

TOP 6 GUI tools for managing Docker – Rancher Components

Start the Rancher container using the following command:

sudo docker run -d --restart=unless-stopped -p 8080:8080 rancherserver:stable

Rancher offers similar features to other web-based GUIs but offers interface elements to add the extra features that Rancher offers. For example, to change the number of WordPress instances, click the plus or minus icons on the container page. The normal resource constraints apply for scaling container instances, e.g. you can’t have more than one container running on a Docker host that uses the same port as another.

Note – Rancher version 1.6 was a container management platform built on Docker but whereas Rancher 2.x builds on Kubernetes.

Here’s the demo of Rancher platform :

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

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

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

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

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

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

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

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

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

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

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

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

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

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

You can now use to pull the image to a new machine and use it to run a new container.

Step 7 — Activating a Dockerized Host

Activating a Docker host connects your local Docker client to that system, which makes it possible to run normal commands on the remote system. To activate a Docker host, type the following command:

Alternatively, you can activate it by using this command:

Tip When working with multiple Docker hosts, the command is the easiest method of switching from one to the other.

After typing any of the above commands, your bash prompt should change to indicate that your Docker client is pointing to the remote Docker host. It will take this form. The name of the host will be at the end of the prompt:

Now any command you type at this command prompt will be executed on that remote host.

If a host is active on the terminal that the command is run, the asterisk under the ACTIVE column shows that it is the active one.

To exit from the remote Docker host, type the following:

You will be returned to the prompt for your local system.

Now let’s create containers on the remote machine.

Step 5 — Executing Additional Docker Machine Commands

You’ve seen how to provision a Dockerized host using the subcommand, and how to list the hosts available to Docker Machine using the subcommand. In this step, you’ll learn a few more useful subcommands.

To obtain detailed information about a Dockerized host, use the subcommand, like so:

The output includes lines like the ones in the following output. The line reveals the version of the Linux distribution used and the line indicates the size slug:

To print the connection configuration for a host, type:

The output will be similar to this:

The last line in the output of the command reveals the IP address of the host, but you can also get that piece of information by typing:

If you need to power down a remote host, you can use to stop it:

Verify that it is stopped:

The output shows that the status of the machine has changed:

To start it again, use the subcommand:

Then review its status again:

You will see that the is now set for the host:

Next let’s look at how to interact with the remote host using SSH.

Step 2 — Installing Additional Docker Machine Scripts

There are three Bash scripts in the Docker Machine GitHub repository you can install to make working with the and commands easier. When installed, these scripts provide command completion and prompt customization.

In this step, you’ll install these three scripts into the directory on your local machine by downloading them directly from the Docker Machine GitHub repository.

Note: Before downloading and installing a script from the internet in a system-wide location, you should inspect the script’s contents first by viewing the source URL in your browser.

The first script allows you to see the active machine in your prompt. This comes in handy when you are working with and switching between multiple Dockerized machines. The script is called . Download it

To complete the installation of this file, you’ll have to modify the value for the variable in your file. The variable is a special shell variable used to modify the Bash command prompt. Open in your editor:

Within that file, there are three lines that begin with . They should look just like these:

~/.bashrc

For each line, insert near the end, as shown in the following example:

~/.bashrc

Save and close the file.

The second script is called . It adds a subcommand to the command, making it significantly easier to switch between Docker hosts. To download it, type:

The third script is called . It adds bash completion for commands. Download it using:

To apply the changes you’ve made so far, close, then reopen your terminal. If you’re logged into the machine via SSH, exit the session and log in again, and you’ll have command completion for the and commands.

Let’s test things out by creating a new Docker host with Docker Machine.

Шаг 2 — Использование команды Docker без sudo (опционально)

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

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

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

Для продолжения работы необходимо ввести пароль пользователя.

Убедиться, что пользователь добавлен в группу docker можно следующим образом:

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

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

Теперь рассмотрим команду .

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

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

Вывод будет выглядеть примерно следующим образом:

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

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

Вывод будет выглядеть следующим образом:

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

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

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

Чтобы остановить запущенный контейнер, используйте с идентификатором или именем контейнера. На этот раз мы будем использовать имя, которое Docker привязал к контейнеру, т.е. :

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

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

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

Step 4 — Learning Docker Compose Commands

Let’s go over the commands the tool supports.

The command works on a per-directory basis. You can have multiple groups of Docker containers running on one machine — just make one directory for each container and one file for each container inside its directory.

So far we’ve been running on our own and using to shut it down. This allows debug messages to be displayed in the terminal window. This isn’t ideal though, when running in production you’ll want to have act more like a service. One simple way to do this is to just add the option when you your session:

will now fork to the background.

To show your group of Docker containers (both stopped and currently running), use the following command:

For example, the following shows that the container is stopped:

A running container will show the state:

To stop all running Docker containers for an application group, issue the following command in the same directory as the file used to start the Docker group:

Note: is also available if you need to shut things down more forcefully.

In some cases, Docker containers will store their old information in an internal volume. If you want to start from scratch you can use the command to fully delete all the containers that make up your container group:

If you try any of these commands from a directory other than the directory that contains a Docker container and file, it will complain and not show you your containers:

Try buildx

There are multiple examples of buildx available, but here is a simple one for C programmers!  Create a file named hello.c with this code:

/*
 * hello.c
 */
#include <stdio.h>
#include <stdlib.h>
 
#ifndef ARCH
#define ARCH "Undefined"
#endif  

int main() {
  printf("Hello, my architecture is %s\n", ARCH);
  exit(0);
}

Here is a Docker file to build and run it. Let’s get used to using multi-stage Docker files as it will be common for deploying embedded applications. Create a Dockerfile with the following:

#
# Dockerfile
#
FROM alpine AS builder 
RUN apk add build-base 
WORKDIR /home
COPY hello.c .
RUN gcc "-DARCH=\"`uname -a`\"" hello.c -o hello
 
FROM alpine 
WORKDIR /home
COPY --from=builder /home/hello .
ENTRYPOINT ["./hello"] 

Now, use buildx to build for multiple architectures and push to Docker hub.

Use docker login first if needed and substitute your own Hub account.

$ docker buildx build --platform linux/arm,linux/arm64,linux/amd64 -t timtsai2018/hello . --push 
$ docker buildx imagetools inspect timtsai2018/hello
Name: docker.io/timtsai2018/hello:latest
MediaType: application/vnd.docker.distribution.manifest.list.v2+json
Digest: sha256:6f2ad12a9400330107ca8ad1675ab2924ae18c61bc1d3c600fdf9e2212e3bb7a

Manifests: 
Name: docker.io/timtsai2018/hello:latest@sha256:adcdcf8f511cb35f7cf124df3d339bf677a733ab40260e85945e0037cf02c598
MediaType: application/vnd.docker.distribution.manifest.v2+json
Platform: linux/arm/v7

Name: docker.io/timtsai2018/hello:latest@sha256:3dc400e687a365aa5140718fde6cbbe37e050606f00274956e17fa9510df9573
MediaType: application/vnd.docker.distribution.manifest.v2+json
Platform: linux/arm64

Name: docker.io/timtsai2018/hello:latest@sha256:9446cf48281105b4f41f1c697c1258e6d2f9b9389d1c0aa34e2209477ed720cb
MediaType: application/vnd.docker.distribution.manifest.v2+json
Platform: linux/amd64

Run using the sha from the manifest and see the output from uname as armv7l, aarch64, and x86_64:

$ docker run docker.io/timtsai2018/hello:latest@sha256:adcdcf8f511cb35f7cf124df3d339bf677a733ab40260e85945e0037cf02c598 
Hello, my architecture is Linux buildkitsandbox 4.15.0-50-generic #54-Ubuntu SMP Mon May 6 18:46:08 UTC 2019 armv7l Linux

$ docker run docker.io/timtsai2018/hello:latest@sha256:3dc400e687a365aa5140718fde6cbbe37e050606f00274956e17fa9510df9573 
Hello, my architecture is Linux buildkitsandbox 4.15.0-50-generic #54-Ubuntu SMP Mon May 6 18:46:08 UTC 2019 aarch64 Linux

$ docker run docker.io/timtsai2018/hello:latest@sha256:9446cf48281105b4f41f1c697c1258e6d2f9b9389d1c0aa34e2209477ed720cb
Hello, my architecture is Linux buildkitsandbox 4.15.0-50-generic #54-Ubuntu SMP Mon May 6 18:46:08 UTC 2019 x86_64 Linux

Paso 8: Introducir imágenes de Docker en un repositorio de Docker

El siguiente paso lógico después de crear una nueva imagen a partir de una imagen existente es compartirla con algunos de sus amigos, con todo el mundo en Docker Hub, o en otro registro de Docker al que tenga acceso. Para introducir una imagen a Docker Hub o a cualquier otro registro de Docker, deberá tener una cuenta en el sistema.

En esta sección verá cómo introducir una imagen de Docker en Docker Hub. Para aprender a crear su propio registro privado de Docker, consulte Cómo configurar un registro de Docker privado en Ubuntu 14.04.

Para introducir su imagen, primero inicie sesión en Docker Hub.

Se le solicitará autenticarse usando su contraseña de Docker Hub. Si especificó la contraseña correcta, la autenticación tendrá éxito.

Nota: Si su nombre de usuario de registro de Docker es diferente del nombre de usuario local que usó para crear la imagen, deberá etiquetar su imagen con su nombre de usuario de registro. Para el ejemplo que se muestra en el último paso, deberá escribir lo siguiente:

Luego podrá introducir su propia imagen usando lo siguiente:

Para introducir la imagen en el repositorio de sammy, el comando sería el siguiente:

El proceso puede tardar un tiempo en completarse cuando se suben las imágenes, pero una vez que finalice el resultado será el siguiente:

Una vez que introduce una imagen en un registro, esta debe aparecer en el panel de su cuenta, como se muestra en la siguiente captura:

Si un intento de introducción produce un error de este tipo, es probable que no haya iniciado sesión:

Inicie sesión con y repita el intento de introducción. Luego, compruebe que exista en su página de repositorios de Docker Hub.

Ahora podrá usar ​​​​​​​ para introducir la imagen en una nueva máquina y usarla para ejecutar un nuevo contenedor.

Step 4 — Specifying the Base OS and Droplet Options When Creating a Dockerized Host

By default, the base operating system used when creating a Dockerized host with Docker Machine is supposed to be the latest Ubuntu LTS. However, at the time of this publication, the command is still using Ubuntu 16.04 LTS as the base operating system, even though Ubuntu 18.04 is the latest LTS edition. So if you need to run Ubuntu 18.04 on a recently-provisioned machine, you’ll have to specify Ubuntu along with the desired version by passing the flag to the command.

For example, to create a machine using Ubuntu 18.04, type:

You’re not limited to a version of Ubuntu. You can create a machine using any operating system supported on DigitalOcean. For example, to create a machine using Debian 8, type:

To provision a Dockerized host using CentOS 7 as the base OS, specify as the image name, like so:

The base operating system is not the only choice you have. You can also specify the size of the Droplet. By default, it is the smallest Droplet, which has 1 GB of RAM, a single CPU, and a 25 GB SSD.

Find the size of the Droplet you want to use by looking up the corresponding slug in the .

For example, to provision a machine with 2 GB of RAM, two CPUs, and a 60 GB SSD, use the slug :

To see all the flags specific to creating a Docker Machine using the DigitalOcean driver, type:

Tip: If you refresh the Droplet page of your DigitalOcean dashboard, you will see the new machines you created using the command.

Now let’s explore some of the other Docker Machine commands.

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 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 command with the 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 subcommand.

Execute the following command to download the official 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 subcommand. As you saw with the example, if an image has not been downloaded when is executed with the 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.

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

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

Adblock
detector