从另一个容器连接到数据库

时间:2020-10-12 16:45:43

标签: docker docker-compose

请尽可能帮我。

我需要用一个数据库启动2个应用程序。

我有2个申请。第一个domain.com,第二个api.domain.com。每个应用程序都有docker-compose.yaml文件。

domain.com-CMS

version: "3.8"

services:
  web:
    container_name: domain_web
    build:
      context: ./docker/php
      dockerfile: Dockerfile
    working_dir: /var/www/html
    #command: composer install
    volumes:
      - ./:/var/www/html
      - ./docker/php/app.conf:/etc/apache2/sites-available/000-default.conf
      - ./docker/php/hosts:/etc/hosts
    networks:
      domain:
        ipv4_address: 10.9.0.5

networks:
  domain:
    driver: bridge
    ipam:
      config:
        - subnet: 10.9.0.0/16
          gateway: 10.9.

volumes:
  bel_baza:

api.domain.com-Laravel 5.6

version: "3.8"

services:
  web:
    container_name: api_domain_web
    build:
      context: ./docker/php
      dockerfile: Dockerfile
    working_dir: /var/www/html
#    command: composer install
    volumes:
      - ./:/var/www/html
      - ./docker/php/app.conf:/etc/apache2/sites-available/000-default.conf
      - ./docker/php/hosts:/etc/hosts
    networks:
      api_domain:
        ipv4_address: 10.15.0.5
  db:
    image: mysql:5.7
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    container_name: api_domain_db
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: domain
      MYSQL_USER: user
      MYSQL_PASSWORD: user

    volumes:
      - api_domain_baza:/var/lib/mysql
      - ./docker/db:/docker-entrypoint-initdb.d

    networks:
      api_domain:
        ipv4_address: 10.15.0.6

  phpmyadmin:
    image: phpmyadmin
    restart: always
    container_name: api_domain_pma
    networks:
      api_domain:
        ipv4_address: 10.15.0.7
  redis:
    image: redis:3.0
    container_name: api_domain_redis
    networks:
     api_domain:
        ipv4_address: 10.15.0.10
networks:
  api_domain:
    driver: bridge
    ipam:
      config:
        - subnet: 10.15.0.0/16
          gateway: 10.15.0.1

volumes:
  api_domain_baza:

api_domain已成功启动。

我需要将domain.com与数据库api_domain_db连接。对于连接主机,我使用IP地址10.15.0.6。第一个应用程序未从第二个应用程序连接到数据库。

我怎么了?

如何将domain.com与第二个应用程序的数据库连接?

1 个答案:

答案 0 :(得分:0)

您的问题是您为每个应用程序使用单独的docker compose应用程序。默认情况下,这些应用程序不能互相访问内部部分:

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

doc在这里-https://docs.docker.com/compose/networking/

因此,就像为每个docker组合创建单独的网络一样。

  1. 如果希望他们俩都能看到彼此的内部,则可以这样创建外部docker网络:
docker network create --subnet 10.1.0.0/24 network_name
  1. 然后在两个docker中使用该网络,组成如下:
networks:
  default:
    external:
      name: network_name
services:
.....
  1. 如果需要固定IP,可以将它们定义为
   app:
    image: ...
    networks:
      default:
        ipv4_address: 10.1.0.10