在Docker容器中解析站点主机名

时间:2020-05-25 07:02:28

标签: docker nginx docker-compose dns resolve

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


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

1 directory, 4 files

  • site.conf:
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;
    }
}

  • docker-compose
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-test.loc通过浏览器解析,但是
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容器解析器:
➜  ~ 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

1 个答案:

答案 0 :(得分:1)

您可以编辑 docker-compose.yml 文件,为网络服务添加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:

谢谢。