Docker 容器:它们如何协同工作?

Docker containers: how do they work together?

我已经开始使用 docker 并构建了一个工作示例,如 https://codeable.io/wordpress-developers-intro-docker 中所示。我需要相当小的 docker 容器,因为部署将在嵌入式系统上进行。

但我不知道这是如何组合在一起的。

有两个 Dockerfile,一个用于 Nginx:

FROM nginx:1.9-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf

nginx.conf定义为:

server {
  server_name _;
  listen 80 default_server;

  root   /var/www/html;
  index  index.php index.html;

  access_log /dev/stdout;
  error_log /dev/stdout info;

  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  location ~ .php$ {
    include fastcgi_params;
    fastcgi_pass my-php:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  }
}

另一个 Dockerfuile 用于 PHP:

Dockerfile.php-fpm:
FROM php:7.0.6-fpm-alpine
RUN docker-php-ext-install -j$(grep -c ^processor /proc/cpuinfo 2>/dev/null || 1) \
    iconv gd mbstring fileinfo curl xmlreader xmlwriter spl ftp mysqli
VOLUME /var/www/html

最后一切都在 docker-compose.yml:

version: '2'
services:
  my-nginx:
    build: .
    volumes:
      - .:/var/www/html
    ports:
      - "8080:80"
    links:
      - my-php
  my-php:
    build:
      context: .
      dockerfile: Dockerfile.php-fpm
    volumes:
      - .:/var/www/html
    ports:
      - "9000:9000"

docker 个容器使用

启动
$ docker-compose build
$ docker-compose up

一切正常 - 这是一种魔法!

以下是我的(一些)问题,以了解正在发生的事情:

  • nginx 容器如何知道 php 容器?

Under links you listed the my-php container, this, among other things, creates a mapping between the name of the container and it's IP in the /etc/hosts file.

  • 当从nginx调用PHP时,PHP在哪个容器中处理运行?

As you would expect, any php code will run in the my-php container, this is defined in the nginx config file, which passes the processing of requests to the php engine running on my-php:9000.

  • 数据如何从 nginx 传递到 PHP 并返回?

Over regular socket communication. Both dockers have their addresses, and they can communicate with each other, like any other computer connected to the network.

  • 这种 docker 用法(一个简单的 Web 服务器应用程序使用 3 个容器)是使用 docker 的正确方法还是对容器的过度杀伤?

I only see 2 containers here. There are some who would say a container should only run one process (like here, so you have built the minimal system), and there are some who say each container should run whatever the service needs. (this however is a matter of preference, and there are different opinions on the matter)

  • 如何扩展此 docker 架构以增加负载?我可以将它用于生产吗?

Yes, you could use it for production. It can scale easily, but in order to achieve scale you are missing some pieces to balance the load. (e.g. a load balancer that can send new requests to an instance which isn't already busy. A very common tool for this is HAProxy.

  • 容器在主机上使用相同的卷 (./)。当使用 PHP 框架作为 Yii2 时,将卷移动到 PHP 或 Nginx 容器不是更好吗?

As the PHP container does all the processing in this case, it should be safe to only mount the volume on my-php.