使用共享的MySQL容器

gaz*_*i86 5 macos docker docker-compose

文艺青年最爱的; 试图让WordPress docker-compose容器与另一个docker-compose容器对话.

在我的Mac上,我有一个WordPress和MySQL容器,我已经构建并配置了一个链接的MySQL服务器.在生产中我计划使用Google Cloud MySQL存储实例,因此计划从docker-compose文件中删除MySQL容器(取消链接),然后将可以在多个docker容器中使用的共享容器分开.

我遇到的问题是我无法将WordPress容器连接到单独的MySQL容器.是否有人能够阐明我将如何解决这个问题?

我尝试创建一个网络并尝试通过/ etc/hosts文件创建一个本地盒引用的固定IP(我的首选配置,因为我可以根据ENV更新文件)

WP:

version: '2'

services:
  wordpress:
    container_name: spmfrontend
    hostname: spmfrontend
    domainname: spmfrontend.local
    image: wordpress:latest
    restart: always
    ports:
      - 8080:80

    # creates an entry in /etc/hosts
    extra_hosts:
      - "ic-mysql.local:172.20.0.1"

    # Sets up the env, passwords etc
    environment:
      WORDPRESS_DB_HOST: ic-mysql.local:9306
      WORDPRESS_DB_USER: root
      WORDPRESS_DB_PASSWORD: root
      WORDPRESS_DB_NAME: wordpress
      WORDPRESS_TABLE_PREFIX: spm

    # sets the working directory
    working_dir: /var/www/html

    # creates a link to the volume local to the file
    volumes:
      - ./wp-content:/var/www/html/wp-content

# Any networks the container should be associated with
networks:
  default:
    external:
      name: ic-network
Run Code Online (Sandbox Code Playgroud)

MySQL的:

version: '2'

services:
  mysql:
    container_name: ic-mysql
    hostname: ic-mysql
    domainname: ic-mysql.local
    restart: always
    image: mysql:5.7
    ports:
      - 9306:3306

    # Create a static IP for the container
    networks:
      ipv4_address: 172.20.0.1

    # Sets up the env, passwords etc
    environment:
      MYSQL_ROOT_PASSWORD: root # TODO: Change this
      MYSQL_USER: root
      MYSQL_PASS: root
      MYSQL_DATABASE: wordpress

    # saves /var/lib/mysql to persistant volume
    volumes:
      - perstvol:/var/lib/mysql
      - backups:/backups

# creates a volume to persist data
volumes:
  perstvol:
  backups:

# Any networks the container should be associated with
networks:
  default:
    external:
      name: ic-network
Run Code Online (Sandbox Code Playgroud)

Dan*_*owe 4

您可能想要做的是创建一个共享的 Docker 网络供两个容器使用,并将它们都指向该网络。您可以使用创建网络docker network create <name>。我将在下面使用sharednet作为示例,但您可以使用任何您喜欢的名称。

一旦网络存在,您就可以将两个容器都指向它。当您使用 docker-compose 时,您可以在 YAML 文件的底部执行此操作。这将位于文件的顶层,即一直到左侧,例如volumes:.

networks:
  default:
    external:
      name: sharednet
Run Code Online (Sandbox Code Playgroud)

要在普通容器(在 compose 之外)上执行相同的操作,您可以传递参数--network

docker run --network sharednet [ ... ]
Run Code Online (Sandbox Code Playgroud)