Перейти к содержимому

Как узнать ip docker контейнера

  • автор:

How to Get A Docker Container IP Address — Explained with Examples

Marcelo Costa Marcelo Costa

How to Get A Docker Container IP Address - Explained with Examples

Docker provides the ability to package and run an application in a loosely isolated environment called a container.

I know what you might be thinking – come on, not another post explaining what Docker is, it’s everywhere these days!

docker-i-see

But don’t worry, we are skipping that basic introduction. The target audience for this article should already have a basic understanding of what Docker and Containers are.

But have you ever wondered how to get a Docker Container IP Address?

Docker network explained

First, let’s understand how the Docker network works. For that we are going to focus on the default bridge network. When you are using Docker, if you don’t specify a driver this is the type of network you are using.

docker-network

Docker network, image from understanding-docker-networking-drivers-use-cases

The bridge network works as a private network internal to the host so containers on it can communicate. External access is granted by exposing ports to containers.

Bridge networks are used when your applications run in standalone containers that need to communicate.

In the picture above db and web can communicate with each other on a user created bridge network called mybridge .

If you’ve never added a network in Docker you should see something similar to this:

The default bridge network is listed, along with host and none . We will ignore the other two, and use the bridge network when we get to the examples.

Docker Container IP Address

By default, the container is assigned an IP address for every Docker network it connects to. And each network is created with a default subnet mask, using it as a pool later on to give away the IP addresses.

Usually Docker uses the default 172.17. 0.0/16 subnet for container networking.

Now to better understand it, we will execute a real use case.

drawing

Docker Example

To illustrate this, we will use a Hive and Hadoop environment, containing 5 Docker Containers.

Check out the docker-compose.yml file we are about to execute:

No one wants to read a HUGE config file, right? So here’s a picture:

Screen-Shot-2020-06-21-at-2.48.18-PM

Much better! Now let’s start up those containers:

We can see 5 containers:

Next let’s check our Docker networks:

Wait a minute. there’s a new network called docker-hive_default !

By default docker compose sets up a single network for your app. And your app’s network is given a name based on the “project name”, originated from the name of the directory it lives in.

So since our directory is named docker-hive , this explains the new network.

Next some examples on how to get the Docker IP Address.

How to Get A Docker Container IP Address — examples

And now that I have your attention, we are going to unveil the mystery.

drawing

1. Using Docker Inspect

Docker inspect is a great way to retrieve low-level information on Docker objects. You can pick out any field from the returned JSON in a fairly straightforward manner.

So shall we use it to get the IP Address from the dockerhive_datanode ?

Didn’t you say that Docker uses the default 172.17. 0.0/16 subnet for container networking? Why is the returned IP Address: 172.18.0.5 outside it?

Screen-Shot-2020-06-22-at-3.25.07-PM

Image created on ip-address-in-cidr-range

To answer that we have to look at our network settings:

We executed this example in a Compute Engine VM, and in this test, the docker network was assigned a different subnet: 172.18.0.0/16. That explains it!

Furthermore, we can also lookup all IP Addresses inside the docker-hive_default network.

So we don’t need to look up each Container’s IP individually:

drawing

If you didn’t notice, we used jq help to parse the Containers map object.

2. Using Docker exec

In the following example we will work with the dockerhive_namenode .

3. Inside the Docker Container

We can even find other containers’ IP Addresses that are inside a container in the same network:

Data node

Hive mestastore

Hive server

Wrap up

All examples were executed in a linux distribution Compute Engine VM. If you execute them in macOS or Windows environments the sample commands might change a bit.

Also bear in mind that those IP Addresses in the examples given are internal to the sample docker-hive_default network. So if you have a use case to connect to those containers externally, you would need to use the host machine’s external IP (assuming that you are exposing the containers ports correctly).

Or if you are using kubernetes, for instance, to manage your Docker containers, let it handle the IP Addresses for you kubernetes-expose-external-ip-address ?.

How to Obtain a Docker Container's IP Address

Docker is an essential tool for software developers and DevOps engineers. Managing and configuring containers is a common task that requires access to their IP addresses. In this blog post, let’s explore multiple methods to obtain the IP address of a Docker container right from the host system.

Method 1: Using docker inspect

Use the docker inspect command combined with the —format option to directly query a container’s IP address. The modern Docker client syntax is:

For the old Docker client syntax, use:

. note If you are on Windows, use double quotes » instead of single quotes ‘ around the curly braces. .

Method 2: Using docker ps and docker inspect

First, get the container ID with docker ps :

The first column in the output shows the container ID. Use it with the docker inspect command to query container information:

Under NetworkSettings, you’ll find the IPAddress. Alternatively, filter the output with grep (for UNIX-based systems) or findstr (for Windows CMD):

Method 3: Using docker inspect in a pipeline

To create a pipeline, first run the container and store its ID in a variable:

Alternatively, simply grep «IPAddress» from docker inspect :

To ignore the case:

Method 4: Obtaining IP addresses of all containers

To find the names and IP addresses of all running Docker containers with one command:

For basic Docker containers:

For docker-compose containers:

The command output will show the container names and their IP addresses:

With the multiple methods outlined in this blog post, you can efficiently query the IP address of a Docker container right from the host system. Knowing these methods and techniques will help improve your container management and configuration processes. Happy Dockering! ��

Sponsorships help us keep the site running and provide resources for developers. Your business can be featured on this spot! Send us an inquiry via this form.

�� Как узнать IP-адрес Docker контейнера

Мануал

Хотите узнать, какой IP-адрес у вашего запущенного контейнера?

Вы можете проверить работающий контейнер, чтобы получить эту информацию.

Команда inspect предоставляет много подробностей о проверяемом контейнере.

Пролистайте к концу вывода и загляните в раздел Networks, чтобы получить IP-адрес контейнера.

Вы также можете использовать команду grep, чтобы вывести только строки, соответствующие шаблону «IPAddress».

Не знаете название или идентификатор контейнера? Используйте команду sudo docker ps.

Не пугайтесь, если у вашего контейнера более одного IP-адреса.

В этом нет ничего необычного.

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

Я объясню вам это в следующем разделе, а затем расскажу о некоторых других методах получения IP-адреса запущено контейнера Docker.

Как общаются Docker контейнеры?

Docker – это инструмент для упаковки и доставки программного обеспечения с использованием технологии контейнеризации.

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

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

В зависимости от назначения программного обеспечения одной службе может потребоваться взаимодействие с другой.

Например, рассмотрим WordPress.

Есть две службы: одна – это веб-сервер, фронтенд, а другая – бэкэнд, база данных.

Интерфейс должен взаимодействовать с базой данных, иначе он просто не будет работать.

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

Эта сеть называется «docker network».

Docker network

Считайте Docker network пулои доступных IP-адресов.

Если два контейнера получат IP-адреса из одного пула, они смогут обмениваться данными друг с другом.

В основном есть два типа сетей: сети по умолчанию или предварительно определенные сети и сети, определяемые пользователем.

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

Проигнорируйте последние две записи и сосредоточьтесь на первой сети.

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

Вы можете получить более подробную информацию об этой сети, выполнив команду docker network inspect bridge.

Я собираюсь отфильтровать вывод, так как для этой демонстрации мне не нужны все данные, которые мы можем вывести.

Если у вас не установлен jq, установите его с помощью диспетчера пакетов вашего дистрибутива.

У каждой из этих сетей есть подсеть, в случае сети bridge это подсеть 172.17.0.0/16.

Это означает, что всего имеется 65534 – 1 = 65533 используемых хостов или IP-адресов.

Я отминусовал один, так как для шлюза выделен 172.17.0.1.

Вы также можете увидеть это, используя следующую команду:

Проверка IP-адреса Docker контейнера

Есть несколько способов проверить IP-адрес[а], связанный с вашим контейнером, вот их список, включая примеры команд.

Метод 1: Inspect

Подкоманда inspect чрезвычайно полезна.

Контейнер можно проверить с помощью команды docker container inspect [CONTAINER ID] | [CONTAINER NAME].

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

Из вывода можно извлечь IP-адрес.

Если вы запустите команду inspect для контейнера, вы получите кучу информации в формате JSON.

Прокрутите вниз, пока не найдете ключ NetworkSettings, там найдите IPAddress.

Это и есть IP-адрес вашего контейнера.

Вот отфильтрованный вывод:

Метод 2: Использование оболочки контейнера

Это наиболее простой метод, но я его не рекомендую.

В этом методе вы присоединяете свой stdin|stdout к контейнеру и запускаете команду ip (или другую команду, которая показывает IP-адреса, связанные с сетевыми адаптерами).

Причина, по которой я не рекомендую это делать, заключается в том, что многие образа довольно легкие и не содержат команду ip (или что-то подобное).

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

Чтобы контейнер работал, я использовал команду sleep 1d.

Теперь запустите процесс оболочки внутри контейнера и прикрепите свой stdin|stdout вот таким образом:

Оказавшись в этом контейнере, попробуйте запустить ip или ifconfig.

Вы увидите что-то вроде следующего:

Чтобы эти команды работали, вам необходимо установить соответствующие пакеты.

Чтобы получить команду ip, установите пакет iproute2 и повторно запустите команду ip a.

Теперь вы можете увидеть, что IP-адрес, связанный с интерфейсом eth0@if5, равен 172.17.0.2.

Обратите внимание на сеть, частью которой является этот контейнер.

Поскольку я не создавал и не подключал пользовательскую сеть к этому контейнеру, он был подключен к сети bridge, поэтому сеть этого IP-адреса 172.17.0.0.

Метод 3: проверив саму сеть

Всякий раз, когда контейнер подключается к сети, этот подключенный контейнер также виден из сети вместе с IP-адресом, назначенным этим контейнерам.

Поскольку мой контейнер подключен к сети bridge, я могу проверить сеть с помощью следующей команды:

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

Вы можете увидеть контейнеры и IP-адреса в указанном выше выводе JSON.

Теперь извлечь IP-адрес конкретного контейнера здесь немного сложнее.

Если вы знаете идентификатор контейнера, вы можете использовать jq следующим образом:

Какой метод выбрать?

Это были все методы, с помощью которых вы можете получить IP-адрес [а] контейнеров.

Второй метод, хотя и интуитивно понятен, не воспроизводится.

В большинстве случаев первый метод самый простой и хорошо выполняет свою работу.

Но может наступить время, когда вы захотите проверить, какие контейнеры подключены к определенной сети, и получить IP-адреса в этой сети.

В этом случае имеет смысл проверить сеть и подсветить IP-адреса.

Вы можете получить все имена контейнеров и назначенные им IP-адреса из сети вот так:

Смените bridge на другую сеть, и вы получите все контейнеры и их IP-адреса.

How to Get Docker Container's IP Address

Getting the IP address of a docker container is easy but it is important to understand a few things about docker networks.

Wondering what’s the IP address of your running docker container? You can inspect the running container to get that information.

The inspect command gives you many details about the container you are inspecting. Go towards the end and look into the Networks section to get the container’s IP address.

You may also use grep command to get just the lines matching the string «IPAddress».

Don’t be alarmed if your container has more than one IP address. That’s not unusual. To understand that, you need to understand how containers communicate with each other.

I’ll explain that to you in the next section followed by some other methods of getting the IP address of a running docker container.

How docker containers communicate?

Docker is a tool for packaging and delivering software to the masses using containerization technology. Software can have a multitude of purposes, from possibly simple text processing to a full web server, hosting your private files. Each of these softwares is broken down into microservices and then packaged as containers. Depending on the purpose of the software, one service may need to communicate with another.

For example, consider WordPress. There are two services, one is the web server that serves the frontend, and another is the backend, the database. The frontend has to communicate with the database, otherwise, it just won’t work.

This communication is achieved by having at least two network interfaces associated with each of these two containers, both interfaces being connected to the same network. This network is called a «docker network».

Docker network

Think of docker network as a pool of available IP addresses. If two containers take on IP addresses from the same pool, they’re going to be able to communicate with each other.

There are mainly two types of networks, the default or predefined networks and the user-defined networks.

You can get the list of networks using the following command

Consider my list below:

Ignore the last two and focus on the first network. The bridge network is the default network every container is going to be connected to if none is specified explicitly. You can get more details about this network by running the docker network inspect bridge command.

I’m going to filter the output since for this demonstration I don’t need all the data that inspect is going to explode out.

Each of these docker networks has a subnet, in the case of the bridge network, this subnet is 172.17.0.0/16. This means there are a total of 65,534 — 1 = 65,533 usable hosts or IP addresses. I deducted one since 172.17.0.1 is allocated for the gateway. You can see that as well using the following command

Checking your docker container’s IP address

There are a couple of ways you can check the IP address[es] associated with your container, here is a list of all of them including command examples.

Method 1: By inspecting the container

The inspect sub-commands of docker are extremely helpful. A container can be inspected using the docker container inspect [CONTAINER ID]|[CONTAINER NAME] command.

Inspecting a container means getting as much information as possible about the container, from ports, environment variables to mount points, cgroup data, etc. IP address can be extracted from it.

If you run the inspect command on a container, you’ll get a bunch of information, in JSON format. Scroll down until you find the key NetworkSettings , there look for the sub-key IPAddress . That’s your container’s IP address.

The command to execute looks like the following

Here’s my output (truncated)

Instead of scrolling through all that, you can filter the output like this:

Here’s a filtered output:

If you want to get an IP address associated with a specific network, use a command like the following

A sample output:

method 2: Using the container’s shell

This is the most straightforward method, but also something I don’t recommend.

In this method, you attach your stdin|stdout with the container’s and run the ip command (or some other command that shows the IP addresses associated with the NICs). This is the generic way of knowing the IP address in Linux command line.

The reason I don’t recommend this is that many images are quite lightweight, and don’t contain the ip command (or something similar).

Take the ubuntu:20.04 image as an example, start a container like the following

To keep the container running I used the sleep 1d command.

Now start a shell process inside the container and attach your stdin|stdout like so

Once you’re in this container, try running ip or ifconfig . You’ll see something like the following:

To get those commands to work, you need to install the relevant packages. To get ip command, install the iproute2 package and rerun the command as ip a

Now you can see the IP address associated with the card [email protected] being 172.17.0.2.

This method surely works, although it’s more work and not very reproducible, it’s intuitive. The next method should be much better compared to this one.

Method 3: By inspecting the network itself

Whenever a container gets connected to a network, that connected container is visible from the network as well, along with the IP address allocated to those containers.

Since my container is connected to the bridge network, I can inspect the network with the following command

Here instead of an id, I’ll use the name, bridge

Instead of scrolling down to the Containers section, I’ll use jq to filter the output this time.

To demonstrate this, I deployed another container with the name ip . You can see the containers and IP addresses in the above JSON object. Now extracting the IP of a specific container is slightly harder here.

If you know the container id, you can use jq like this

Here’s an example

Most of the time you can not remember the container id, so if you want to get the IP from only the container name, you need some knowledge of jq (or just reuse the following command).

Place the container name in the select function and see the magic happen.

Which method do you prefer? Method 1 probably

Those were all the methods through which you can get the IP address[es] of docker containers. The second method although intuitive isn’t reproducible. Most of the time it’s the first method that gets used since it’s the easiest and gets the job done.

But there may come a time when you’d want to check what some containers are connected to a certain network and get the IP addresses on that network. In that case, inspecting the network and getting the IPs makes sense. You can get all the container names and IPs allocated to them from a network like this

Change bridge to some other network, and you’ll get all the containers and their IP addresses like this.

That’s it for today. I hope this article was helpful to you. If you have any questions, do let me know in the comments down below.

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

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

Школа онлайн с государственным аттестатом