Phil
Phil

Reputation: 50346

From inside of a Docker container, how do I connect to the localhost of the machine?

I have a Nginx running inside a docker container. I have a MySql running on the host system. I want to connect to the MySql from within my container. MySql is only binding to the localhost device.

Is there any way to connect to this MySql or any other program on localhost from within this docker container?

This question is different from "How to get the IP address of the docker host from inside a docker container" due to the fact that the IP address of the docker host could be the public IP or the private IP in the network which may or may not be reachable from within the docker container (I mean public IP if hosted at AWS or something). Even if you have the IP address of the docker host it does not mean you can connect to docker host from within the container given that IP address as your Docker network may be overlay, host, bridge, macvlan, none etc which restricts the reachability of that IP address.

Upvotes: 3515

Views: 2755301

Answers (30)

5andr0
5andr0

Reputation: 2018

Reading through all the answers, I found none which mentions that the default docker dns resolver 127.0.0.11 does not resolve hostnames inside /etc/hosts including host.docker.internal. Some applications like nginx communicate with that resolver directly and can't resolve host.docker.internal which will lead to a 502 bad gateway.

Many answers suggested to use the ip 172.17.0.1, but this is not always the gateway ip!

Instead of getting the gateway with scripts, you can simply set the gateway for your docker network manually:

Docker Compose
networks:
  default:
    ipam:
      driver: default
      config:
        - subnet: 172.28.0.0/16
          ip_range: 172.28.5.0/24
          gateway: 172.28.5.254

This allows you to communicate with your host over the fixed ip 172.28.5.254

Create the network externally
docker network create \
  --driver=bridge \
  --subnet=172.28.0.0/16 \
  --ip-range=172.28.5.0/24 \
  --gateway=172.28.5.254 \
  host-gateway

Now just bind your container to the network host-gateway

Upvotes: 0

Lamp
Lamp

Reputation: 645

If the application and database are running on the same Linux kernel, don't use TCP/IP, use Unix sockets. Not only is it faster, it is easier for Docker.

Simply mount the MySQL socket into the container and configure the application to connect to it.

Most likely it is at /run/mysqld/mysqld.sock, but if not, check your mysqld configuration to see where it's located.

To mount it in docker compose:

volumes:
  - "/run/mysqld/mysqld.sock:/run/mysqld/mysqld.sock"

Upvotes: -1

ymochurad
ymochurad

Reputation: 999

On linux if you can ping the host.docker.internal from inside the container, but you can not reach the ports that are opened on your localhost, please make sure you have docker installed not in rootless mode. If it is in rootless mode it is limited. Quote from documentation:

IPAddress shown in docker inspect is namespaced inside RootlessKit's network namespace. This means the IP address is not reachable from the host without nsenter-ing into the network namespace.

Host network (docker run --net=host) is also namespaced inside RootlessKit.

Hope this helps someone, as I spend several days on it

Upvotes: 4

Tony Jara
Tony Jara

Reputation: 119

If it's useful to anyone, when using NEXTJS on mac I had to use http://docker.for.mac.localhost:8000 on the CLIENT and plain old http://localhost:8000 on the server.

Upvotes: 1

Thomasleveil
Thomasleveil

Reputation: 103905

Edit:

If you are using Docker-for-mac or Docker-for-Windows 18.03+, connect to your mysql service using the host host.docker.internal (instead of the 127.0.0.1 in your connection string).

If you are using Docker-for-Linux 20.10.0+, you can also use the host host.docker.internal if you started your Docker container with the --add-host host.docker.internal:host-gateway option, or added the following snippet in your docker-compose.yml file :

extra_hosts:
    - "host.docker.internal:host-gateway"

Otherwise, read below


TLDR

Use --network="host" in your docker run command, then 127.0.0.1 in your docker container will point to your docker host.

Note: This mode only works on Docker for Linux, per the documentation.


Note on docker container networking modes

Docker offers different networking modes when running containers. Depending on the mode you choose you would connect to your MySQL database running on the docker host differently.

docker run --network="bridge" (default)

Docker creates a bridge named docker0 by default. Both the docker host and the docker containers have an IP address on that bridge.

on the Docker host, type sudo ip addr show docker0 you will have an output looking like:

[vagrant@docker:~] $ sudo ip addr show docker0
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
    inet 172.17.42.1/16 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::5484:7aff:fefe:9799/64 scope link
       valid_lft forever preferred_lft forever

So here my docker host has the IP address 172.17.42.1 on the docker0 network interface.

Now start a new container and get a shell on it: docker run --rm -it ubuntu:trusty bash and within the container type ip addr show eth0 to discover how its main network interface is set up:

root@e77f6a1b3740:/# ip addr show eth0
863: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 66:32:13:f0:f1:e3 brd ff:ff:ff:ff:ff:ff
    inet 172.17.1.192/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::6432:13ff:fef0:f1e3/64 scope link
       valid_lft forever preferred_lft forever

Here my container has the IP address 172.17.1.192. Now look at the routing table:

root@e77f6a1b3740:/# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.17.42.1     0.0.0.0         UG    0      0        0 eth0
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0

So the IP Address of the docker host 172.17.42.1 is set as the default route and is accessible from your container.

root@e77f6a1b3740:/# ping 172.17.42.1
PING 172.17.42.1 (172.17.42.1) 56(84) bytes of data.
64 bytes from 172.17.42.1: icmp_seq=1 ttl=64 time=0.070 ms
64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.201 ms
64 bytes from 172.17.42.1: icmp_seq=3 ttl=64 time=0.116 ms

docker run --network="host"

Alternatively you can run a docker container with network settings set to host. Such a container will share the network stack with the docker host and from the container point of view, localhost (or 127.0.0.1) will refer to the docker host.

Be aware that any port opened in your docker container would be opened on the docker host. And this without requiring the -p or -P docker run option.

IP config on my docker host:

[vagrant@docker:~] $ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
       valid_lft forever preferred_lft forever

and from a docker container in host mode:

[vagrant@docker:~] $ docker run --rm -it --network=host ubuntu:trusty ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
       valid_lft forever preferred_lft forever

As you can see both the docker host and docker container share the exact same network interface and as such have the same IP address.


Connecting to MySQL from containers

bridge mode

To access MySQL running on the docker host from containers in bridge mode, you need to make sure the MySQL service is listening for connections on the 172.17.42.1 IP address.

To do so, make sure you have either bind-address = 172.17.42.1 or bind-address = 0.0.0.0 in your MySQL config file (my.cnf).

If you need to set an environment variable with the IP address of the gateway, you can run the following code in a container :

export DOCKER_HOST_IP=$(route -n | awk '/UG[ \t]/{print $2}')

then in your application, use the DOCKER_HOST_IP environment variable to open the connection to MySQL.

Note: if you use bind-address = 0.0.0.0 your MySQL server will listen for connections on all network interfaces. That means your MySQL server could be reached from the Internet ; make sure to set up firewall rules accordingly.

Note 2: if you use bind-address = 172.17.42.1 your MySQL server won't listen for connections made to 127.0.0.1. Processes running on the docker host that would want to connect to MySQL would have to use the 172.17.42.1 IP address.

host mode

To access MySQL running on the docker host from containers in host mode, you can keep bind-address = 127.0.0.1 in your MySQL configuration and connect to 127.0.0.1 from your containers:

[vagrant@docker:~] $ docker run --rm -it --network=host mysql mysql -h 127.0.0.1 -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.5.41-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

note: Do use mysql -h 127.0.0.1 and not mysql -h localhost; otherwise the MySQL client would try to connect using a unix socket.

Upvotes: 4827

Janne Annala
Janne Annala

Reputation: 28687

For all platforms

Docker v 20.10 and above (since December 14th 2020)

Use your internal IP address or connect to the special DNS name host.docker.internal which will resolve to the internal IP address used by the host.

This is for development purpose and does not work in a production environment outside of Docker Desktop.

Linux caveats

To enable this in Docker on Linux, add --add-host=host.docker.internal:host-gateway to your docker command to enable the feature.

To enable this in Docker Compose on Linux, add the following lines to the container definition:

extra_hosts:
    - "host.docker.internal:host-gateway"

According to some users the special DNS name only works within the Docker's default bridge network, not within custom networks.

For older macOS and Windows versions of Docker

Docker v 18.03 and above (since March 21st 2018)

Use your internal IP address or connect to the special DNS name host.docker.internal which will resolve to the internal IP address used by the host.

Linux support pending https://github.com/docker/for-linux/issues/264

For older macOS versions of Docker

Docker for Mac v 17.12 to v 18.02

Same as above but use docker.for.mac.host.internal instead.

Docker for Mac v 17.06 to v 17.11

Same as above but use docker.for.mac.localhost instead.

Docker for Mac 17.05 and below

To access host machine from the docker container you must attach an IP alias to your network interface. You can bind whichever IP you want, just make sure you're not using it to anything else.

sudo ifconfig lo0 alias 123.123.123.123/24

Then make sure that you server is listening to the IP mentioned above or 0.0.0.0. If it's listening on localhost 127.0.0.1 it will not accept the connection.

Then just point your docker container to this IP and you can access the host machine!

To test you can run something like curl -X GET 123.123.123.123:3000 inside the container.

The alias will reset on every reboot so create a start-up script if necessary.

Solution and more documentation here: https://docs.docker.com/desktop/networking/#use-cases-and-workarounds-for-all-platforms

Upvotes: 789

Danon
Danon

Reputation: 2972

On Windows machines, it is common that ports are unreachable because of internal cache problems with network addresses translator. Restarting it might help:

net stop winnat
net start winnat

Upvotes: 0

DeyaEldeen
DeyaEldeen

Reputation: 11807

Use

host.docker.internal

instead of

localhost

Upvotes: 382

Ad&#225;n Escobar
Ad&#225;n Escobar

Reputation: 4573

you can use net alias for your machine

OSX

sudo ifconfig lo0 alias 123.123.123.123/24 up

LINUX

sudo ifconfig lo:0  123.123.123.123 up

then from the container you can see the machine by 123.123.123.123

Upvotes: 2

Maksym Kosenko
Maksym Kosenko

Reputation: 595

An additional point might be useful, especially for NGINX server configuration within a docker container. So, if your host service is supposed to read a client's url for different purposes, there is a possibility to define it, just slightly modifying the approach mentioned before in the answers:

--add-host brand-A-client.local:host-gateway

or in a docker-compose.yml

extra_hosts:
- brand-B-client.local:host-gateway

And refer to them respectively within containers. Applicable for Docker Windows/Macos/Linux.

Upvotes: 2

Nigrimmist
Nigrimmist

Reputation: 12328

Unfortunately, currently, Windows (at least docker desktop) is not supporting --net=host

Quoted from: https://docs.docker.com/network/network-tutorial-host/#prerequisites

The host networking driver only works on Linux hosts, and is not supported on Docker for Mac, Docker for Windows, or Docker EE for Windows Server.

You can try to use https://docs.docker.com/toolbox/

Upvotes: 2

Felipe Toledo
Felipe Toledo

Reputation: 615

Very simple and quick, check your host IP with ifconfig (linux) or ipconfig (windows) and then create a docker-compose.yml:

version: '3' # specify docker-compose version
services:
  nginx:
    build: ./ # specify the directory of the Dockerfile
    ports:
      - "8080:80" # specify port mapping
    extra_hosts:
      - "dockerhost:<yourIP>"

This way, your container will be able to access your host. When accessing your DB, remember to use the name you specified before, in this case dockerhost and the port of your host in which the DB is running.

Upvotes: 25

Casey
Casey

Reputation: 1773

For those on Windows, assuming you're using the bridge network driver, you'll want to specifically bind MySQL to the IP address of the hyper-v network interface.

This is done via the configuration file under the normally hidden C:\ProgramData\MySQL folder.

Binding to 0.0.0.0 will not work. The address needed is shown in the docker configuration as well, and in my case was 10.0.75.1.

Upvotes: 15

Elad
Elad

Reputation: 753

None of the answers worked for me when using Docker Toolbox on Windows 10 Home, but 10.0.2.2 did, since it uses VirtualBox which exposes the host to the VM on this address.

Upvotes: 18

dansalmo
dansalmo

Reputation: 11686

Simplest solution for Mac OSX

Just use the IP address of your Mac. On the Mac run this to get the IP address and use it from within the container:

ifconfig | grep 'inet 192'| awk '{ print $2}'

As long as the server running locally on your Mac or in another docker container is listening to 0.0.0.0, the docker container will be able to reach out at that address.

If you just want to access another docker container that is listening on 0.0.0.0 you can use 172.17.0.1

Upvotes: 34

midi
midi

Reputation: 4038

For me enetring this command on the host to get the ip did the trick:

docker run busybox ping -c 1 host.docker.internal | awk 'FNR==2 {print $4}' | sed s'/.$//'

or on mac

docker run busybox ping -c 1 docker.for.mac.localhost | awk 'FNR==2 {print $4}' | sed s'/.$//'

docker-compose.yml

version: '3.8'

services:
  spring-app-container:
    image: spring-app:1
    build:
      context: ./
      dockerfile: Dockerfile
    ports:
      - "50800:50800"

Upvotes: 1

Ray D
Ray D

Reputation: 664

Solution for Linux (kernel >=3.6).

Ok, your localhost server has a default docker interface docker0 with IP address 172.17.0.1. Your container started with default network settings --net="bridge".

  1. Enable route_localnet for docker0 interface:

    $ sysctl -w net.ipv4.conf.docker0.route_localnet=1
    
  2. Add these rules to iptables:

    $ iptables -t nat -I PREROUTING -i docker0 -d 172.17.0.1 -p tcp --dport 3306 -j DNAT --to 127.0.0.1:3306
    $ iptables -t filter -I INPUT -i docker0 -d 127.0.0.1 -p tcp --dport 3306 -j ACCEPT
    
  3. Create MySQL user with access from '%' that means - from anyone, excluding localhost:

    CREATE USER 'user'@'%' IDENTIFIED BY 'password';
    
  4. Change in your script the mysql-server address to 172.17.0.1.

From the kernel documentation:

route_localnet - BOOLEAN: Do not consider loopback addresses as martian source or destination while routing. This enables the use of 127/8 for local routing purposes (default FALSE).

Upvotes: 63

Prince
Prince

Reputation: 317

If you're running with --net=host, localhost should work fine. If you're using default networking, use the static IP 172.17.0.1.

See this - https://stackoverflow.com/a/48547074/14120621

Upvotes: 17

Yılmaz Durmaz
Yılmaz Durmaz

Reputation: 2994

In 7 years the question was asked, it is either docker has changed, or no one tried this way. So I will include my own answer.

I have found all answers use complex methods. Today, I have needed this, and found 2 very simple ways:

  • use ipconfig or ifconfig on your host and make note of all IP addresses. At least two of them can be used by the container.

    • I have a fixed local network address on WiFi LAN Adapter: 192.168.1.101. This could be 10.0.1.101. the result will change depending on your router
    • I use WSL on windows, and it has its own vEthernet address: 172.19.192.1
  • use host.docker.internal. Most answers have this or another form of it depending on OS. The name suggests it is now globally used by docker.

A third option is to use WAN address of the machine, or in other words IP given by the service provider. However, this may not work if IP is not static, and requires routing and firewall settings.

Upvotes: 8

Tires
Tires

Reputation: 1602

Despite lot of long, confusing answers a short one. If your docker bridge network is 172.17.0.0/16, do the following things:

  1. Bind your container to 172.17.0.1 eg. -p 172.17.0.1:8080:8080 (whatever is the gateway in your Docker bridge network)
  2. Just access 172.17.0.1 port 8080 eg. curl http://172.17.0.1:8080/ from other container

Upvotes: 1

MichaelMoser
MichaelMoser

Reputation: 3500

the server on the host is listening on port 5000; it will send a string response from host back as a response

echo "response from host" | nc -l -p 5000

the docker is running in bridge mode by default (that is more secure than running in host network mode); the process in the docker gets the ipv4 address for the first network interface on the host that is not 127.0.0.1; this ipv4 address is passed to the docker via environment variable HOSTIP ; inside the docker there is a nc command that connects to the server on the host ip and port 5000; the command also reads the response of the server.

HOST=$(ifconfig | grep 'inet ' | grep -v 127.0.0.1 | awk '{ print $2 }' | head -1 | sed -n 's/[^0-9]*\([0-9\.]*\)/\1/p'); docker run -e HOSTIP="${HOST}" --rm -it alpine /bin/sh -c 'echo "greetings from container" | nc $HOSTIP 5000 -v'

The expression that computes the ipv4 address of the first listed interface does work on osx and linux:

HOST=$(ifconfig | grep 'inet ' | grep -v 127.0.0.1 | awk '{ print $2 }' | head -1 | sed -n 's/[^0-9]*\([0-9\.]*\)/\1/p')

to make it even more general: you can run the server inside another docker container, that would look as follows:

docker run --expose 5000 -p :5000:5000 --rm -it alpine /bin/sh -c 'echo "response from host" | nc -l -p 5000'

--expose 5000 the docker container can accept connection on port 5000

-p :5000:5000 the docker engine on the host side is listening on port 5000 on any interface and is forwarding connections to port 5000 on the container network (where nc is running).

Upvotes: 1

balki
balki

Reputation: 27674

Connect to the gateway address.

❯ docker network inspect bridge | grep Gateway
                    "Gateway": "172.17.0.1"

Make sure the process on the host is listening on this interface or on all interfaces and is started after docker. If using systemd, you can add the below to make sure it is started after docker.

[Unit]
After=docker.service

Example

❯ python -m http.server &> /dev/null &
[1] 149976

❯ docker run --rm python python -c  "from urllib.request import urlopen;print(b'Directory listing for' in urlopen('http://172.17.0.1:8000').read())" 
True

Upvotes: 5

Duc Trung Mai
Duc Trung Mai

Reputation: 2558

You can simply do ifconfig on host machine to check your host IP, then connect to the ip from within your container, works perfectly for me.

Upvotes: 4

Ehsan88
Ehsan88

Reputation: 3781

First see this answer for the options that you have to fix this problem. But if you use docker-compose you can add network_mode: host to your service and then use 127.0.0.1 to connect to the local host. This is just one of the options described in the answer above. Below you can find how I modified docker-compose.yml from https://github.com/geerlingguy/php-apache-container.git:

 ---
 version: "3"
 services:
   php-apache:
+    network_mode: host
     image: geerlingguy/php-apache:latest
     container_name: php-apache
...

+ indicates the line I added.


[Additional info] This has also worked in version 2.2. and "host" or just 'host' are both worked in docker-compose.

 ---
 version: "2.2"

 services:
   php-apache:
+    network_mode: "host"
        or
+    network_mode: host
...

Upvotes: 13

BMitch
BMitch

Reputation: 263469

Several solutions come to mind:

  1. Move your dependencies into containers first
  2. Make your other services externally accessible and connect to them with that external IP
  3. Run your containers without network isolation
  4. Avoid connecting over the network, use a socket that is mounted as a volume instead

The reason this doesn't work out of the box is that containers run with their own network namespace by default. That means localhost (or 127.0.0.1 pointing to the loopback interface) is unique per container. Connecting to this will connect to the container itself, and not services running outside of docker or inside of a different docker container.

Option 1: If your dependency can be moved into a container, I would do this first. It makes your application stack portable as others try to run your container on their own environment. And you can still publish the port on your host where other services that have not been migrated can still reach it. You can even publish the port to the localhost interface on your docker host to avoid it being externally accessible with a syntax like: -p 127.0.0.1:3306:3306 for the published port.

Option 2: There are a variety of ways to detect the host IP address from inside of the container, but each have a limited number of scenarios where they work (e.g. requiring Docker for Mac). The most portable option is to inject your host IP into the container with something like an environment variable or configuration file, e.g.:

docker run --rm -e "HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')" ...

This does require that your service is listening on that external interface, which could be a security concern. For other methods to get the host IP address from inside of the container, see this post.

Slightly less portable is to use host.docker.internal. This works in current versions of Docker for Windows and Docker for Mac. And in 20.10, the capability has been added to Docker for Linux when you pass a special host entry with:

docker run --add-host host.docker.internal:host-gateway ...

The host-gateway is a special value added in Docker 20.10 that automatically expands to a host IP. For more details see this PR.

Option 3: Running without network isolation, i.e. running with --net host, means your application is running on the host network namespace. This is less isolation for the container, and it means you cannot access other containers over a shared docker network with DNS (instead, you need to use published ports to access other containerized applications). But for applications that need to access other services on the host that are only listening on 127.0.0.1 on the host, this can be the easiest option.

Option 4: Various services also allow access over a filesystem based socket. This socket can be mounted into the container as a bind mounted volume, allowing you to access the host service without going over the network. For access to the docker engine, you often see examples of mounting /var/run/docker.sock into the container (giving that container root access to the host). With mysql, you can try something like -v /var/run/mysqld/mysqld.sock:/var/run/mysqld/mysql.sock and then connect to localhost which mysql converts to using the socket.

Upvotes: 29

L.T
L.T

Reputation: 2589

if you use docker-compose, maybe it can work:

iptables -I INPUT ! -i eth0 -p tcp --dport 8001 -j ACCEPT

the eth0 is your network interface that connect internet, and 8081 the host server port

the best way for iptables rule is iptables TRACE

Upvotes: 2

wiseCoder
wiseCoder

Reputation: 21

To make everything work, you need to create a config for your server (caddy, nginx) where the main domain will be "docker.for.mac.localhost". For this replace in baseURL "http://localhost/api" on "http://docker.for.mac.localhost/api"

docker-compose.yml

backend:
  restart: always
  image: backend
  build:
    dockerfile: backend.Dockerfile
    context: .
  environment:
    # add django setting.py os.getenv("var") to bd config and ALLOWED_HOSTS CORS_ORIGIN_WHITELIST
    DJANGO_ALLOWED_PROTOCOL: http
    DJANGO_ALLOWED_HOSTS: docker.for.mac.localhost
    POSTGRES_PASSWORD: 123456
    POSTGRES_USER: user
    POSTGRES_DB: bd_name
    WAITDB: "1"
  volumes:
    - backend_static:/app/static
    - backend_media:/app/media
  depends_on:
    - db

frontend:
  restart: always
  build:
    dockerfile: frontend.Dockerfile
    context: .
  image: frontend
  environment:
    #  replace baseURL for axios
    API_URL: http://docker.for.mac.localhost/b/api
    API_URL_BROWSER: http://docker.for.mac.localhost/b/api
    NUXT_HOST: 0.0.0.0
  depends_on:
    - backend

caddy:
  image: abiosoft/caddy
  restart: always
  volumes:
    - $HOME/.caddy:/root/.caddy
    - ./Caddyfile.local:/etc/Caddyfile
    - backend_static:/static
    - backend_media:/media
  ports:
  - 80:80
  depends_on:
    - frontend
    - backend
    - db

Caddyfile.local

http://docker.for.mac.localhost {

  proxy /b backend:5000 {
    header_upstream Host {host}
    header_upstream X-Real-IP {remote}
    header_upstream X-Forwarded-For {remote}
    header_upstream X-Forwarded-Port {server_port}
    header_upstream X-Forwarded-Proto {scheme}
  }

  proxy / frontend:3000 {
    header_upstream Host {host}
    header_upstream X-Real-IP {remote}
    header_upstream X-Forwarded-For {remote}
    header_upstream X-Forwarded-Port {server_port}
    header_upstream X-Forwarded-Proto {scheme}
  }

  root /

  log stdout
  errors stdout
  gzip
}

http://docker.for.mac.localhost/static {
  root /static
}

http://docker.for.mac.localhost/media {
  root /media
}

django settings.py

ALLOWED_HOSTS = [os.getenv("DJANGO_ALLOWED_HOSTS")]
    
CORS_ORIGIN_WHITELIST = [f'{os.getenv("DJANGO_ALLOWED_PROTOCOL")}://{os.getenv("DJANGO_ALLOWED_HOSTS")}']

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "NAME": os.getenv("POSTGRES_DB"),
        "USER": os.getenv("POSTGRES_USER"),
        "PASSWORD": os.getenv("POSTGRES_PASSWORD"),
        "HOST": "db",
        "PORT": "5432",
    }
}

nuxt.config.js (the baseURL variable will override API_URL of environment)

axios: {
  baseURL: 'http://127.0.0.1:8000/b/api'
},

Upvotes: 2

Binh Ho
Binh Ho

Reputation: 4936

Try this:

version: '3.5'
services:
  yourservice-here:
    container_name: container_name
    ports:
      - "4000:4000"
    extra_hosts: # <---- here
      - localhost:192.168.1.202
      - or-vitualhost.local:192.168.1.202

To get 192.168.1.202, uses ifconfig

This worked for me. Hope this help!

Upvotes: 11

Praveenkumar Beedanal
Praveenkumar Beedanal

Reputation: 834

For windows,

I have changed the database url in spring configuration: spring.datasource.url=jdbc:postgresql://host.docker.internal:5432/apidb

Then build the image and run. It worked for me.

Upvotes: 22

F. Kam
F. Kam

Reputation: 656

The way I do it is pass the host IP as environment variable to container. Container then access the host by that variable.

Upvotes: 0

Related Questions