How to Access Docker Containers? IP Address or Container Name?

Introduction

This post covers various scenarios for accessing Docker containers, exploring whether to use the container’s IP address or name in each case. While this information might be trivial for seasoned Docker users, I often find myself forgetting these basic concepts, wasting a lot of time. Hence, I decided to write a blog post in the form of a cheat sheet. Most of the content here is generated by ChatGPT.

In general, just remember these two points:

  • Although we prefer to access containers by their names, this DNS service is provided by Docker and can only be used by containers.
  • For port mapping -p 8080:80: Use the container’s port 80 when accessing the container via container name/IP, and use the host’s port 8080 when accessing from the host.

Accessing the Target Container from Another Container

Here, we should distinguish whether the two containers are on the same Docker network.

Both Containers are on the Same Network

Scenario 1: Both Containers are Part of the Same Compose

1
2
3
4
5
6
7
8
version: '3'
services:
web:
image: mywebapp
ports:
- "8080:80"
db:
image: mysql

Scenario 2: Use the --network Option When Creating Containers to Place Them on the Same Network

1
2
3
docker network create my_network
docker run -d --name web --network my_network mywebapp
docker run -d --name db --network my_network mysql

In both cases, you can access the containers by their names (using the container’s port).

1
curl http://web:80

Note: If the target container is on the bridge network, this does not apply. You need to access it via IP.

Containers are Not on the Same Network

You need to use the target container’s IP.

First, obtain the container’s IP, then access it via IP:

1
2
CONTAINER_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container)
curl http://$CONTAINER_IP:80

Accessing the Target Container from the Host

There are two methods:

  1. Access via the container’s IP.

  2. Use the host’s port to access:

1
curl http://localhost:8080

Note, in this case, this is the host’s port, not the container’s port.

Accessing the Target Container from an External Host

Use the host’s IP to access:

1
curl http://host_ip:8080

References

  • ChatGPT