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.

1

3 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.