在 docker 容器内解析站点主机名

resolve site hostname inside docker container

无法在 docker nginx(以及同一网络中的其他)容器内解析站点 nginx 主机。


➜  dockerised-php git:(master) ✗ tree .
.
├── code
│   └── index.php
├── docker-compose.yml
├── README.md
└── site.conf

1 directory, 4 files

server {
    listen 80;
    index index.php index.html;
    server_name docker-test.loc;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /code;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - ./code:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - code-network
    php:
        image: php:fpm
        volumes:
            - ./code:/code
        networks:
            - code-network

networks:
  code-network:
docker exec -it dockerised-php_web_1 bash

nslookup docker-test.loc
# connection timed out; no servers could be reached
➜  ~ nslookup docker-test.loc
Server:     127.0.0.53
Address:    127.0.0.53#53

Non-authoritative answer:
Name:   docker-test.loc
Address: 127.0.0.1

➜  ~ docker exec -it dockerised-php_web_1 bash
root@6340952094ed:/# cat /etc/resolv.conf 
search Dlink
nameserver 127.0.0.11
options ndots:0

我在 nginx 容器中尝试 cat "127.0.0.1 docker-test.loc" >> /etc/hosts,但没有帮助。

我应该怎么做才能解决 docker-test.loc 容器内的问题?

您可以编辑 docker-compose.yml 文件来为 Web 服务添加 container_name 这样的:

version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        container_name: docker-test.loc
        volumes:
            - ./code:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - code-network
    php:
        image: php:fpm
        volumes:
            - ./code:/code
        networks:
            - code-network

networks:
  code-network:

然后 code-network 中的所有容器都可以将 docker-test.loc 解析为您的 docker 组合中的 web-服务容器的 IP 地址。

编辑 对于 nginx 容器中的多个主机名(虚拟主机),您可以像这样使用 external_links

version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - ./code:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - code-network
    php:
        image: php:fpm
        volumes:
            - ./code:/code
        networks:
            - code-network
        external_links:
            - web:docker-test__1.loc
            - web:docker-test__2.loc
            - web:abcdef.vn

networks:
  code-network:

谢谢。