HiveBrain v1.2.0
Get Started
← Back to all entries
snippetdockerMinor

From inside a Docker container, how can I consume an API that is on the machine's localhost?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
canthecontainerlocalhostdockerthathowmachinefromapi

Problem

First of all, please forgive me if any information is missing or if my question does not meet the standards required by the site. I have very basic knowledge of docker, linux and networking and I am lost.

I use Ubuntu version 20.2 and I have docker version 20.10.10.

I have a system (CakePHP) running in a docker container, and an API (LARAVEL) running on my machine's local host (outside of the docker container), and I need to consume that API on the system from inside the docker container.

This is the content of docker-compose.yml

version: '2'
services:
  server-c10-php56:
    build:
      context: .
      dockerfile: Dockerfile
    image: php-c10-56
    volumes:
      - /srv/:/srv/
      - /var/www/html/:/var/www/html/
    ports:
      - "9056:80"
      - "9443:443"
    networks:
      - net30
    container_name: "docker-php56"
networks:
  sdnet:
    driver: "bridge"
  net30:
    ipam:
      driver: default
      config:
        - subnet: 172.30.0.0/16


As I understand it, the system (CakePHP) is running inside this 172.30.0.0/16 subnet.
And the system (CakePHP) to connect to PostgreSQL, connects through IP 172.30.0.1 (I think it's the gateway to access the local host of my machine).

The API I can consume normally by Postman.
Here is a screenshot of a test.

And on the system (CakePHP) from inside the docker container, I'm trying to consume like this (just testing for now).

It takes a while trying to connect, but without success. This is the return obtained ( sorry for the array format).

```
Array
(
[response] =>
[info] => Array
(
[url] => http://172.30.0.1:8000/api/queue/integracaoEcommerce
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 130.124754
[namelookup_time] => 1.8E-5
[connect_time] => 0

Solution

I'm not sure I can help you, but this might :

https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach

tldr (bridge mode):

to get the ip of the container (in container CLI) :
ip addr show eth0

to get the ip of the host's docker interface (host CLI) :
sudo ip addr show docker0

Context

StackExchange DevOps Q#15140, answer score: 4

Revisions (0)

No revisions yet.