0

I have two docker containers, nginx and php, from which I want to access mysql server running on host machine and sql server on remote machine.

Have tried change the network type from "bridge" to "host" but it returns errors.

version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - /var/www/:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - mynetwork
    php:
        image: php:fpm
        volumes:
            - /var/www/:/code
        networks:
           - mynetwork
networks:
    mynetwork:
       driver: bridge

I'm expecting php code running in my containers can connect to those two databases.

Note: I don't using docker run to run container, instead I'm using docker-compose up -d so I just want to edit the docker-compose.yml file.

Arief Karfianto
  • 235
  • 2
  • 8
  • Possible duplicate of [From inside of a Docker container, how do I connect to the localhost of the machine?](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach) – David Maze May 27 '19 at 10:09

3 Answers3

1

Just make sure the container can access the external database by going online.Bridge" and "host network type can do. First, you need to make sure you have a correct mysql grant rule, such as %. 1\You can use the ip of the host to access the mysql on the host from the inside of the container. 2\Other mysql instances that belong to the same LAN as the host, access from the container can also be accessed using the LAN ip on the mysql instance. Ensure the ping is normal,Make sure the ping is working, otherwise your docker installation may have problems, such as problems from iptables.

lmlmvxi
  • 11
  • 3
1

In your php service declaration you have to add something like:

extra_hosts:
      - "local_db:host_ip"

Where local_db is the name you will configure in your database connection string and host_ip is the IP of your host on the local network.

You have to make sure that your php code does not try to connect to "localhost" because that will not work. You need to use the server name "local_db" (in my example).

You do the same thing for the remote database, just make sure the IP is reachable.

You can remove the network declaration because it is not needed.

Mihai
  • 9,526
  • 2
  • 18
  • 40
0

In order to docker containers has access to each other you should link them. docker service uses link switch to add ID and IP of one container in /etc/hosts file of another.

Siyavash vaez afshar
  • 1,303
  • 10
  • 12