【问题标题】:Issue with nginx config using docker使用 docker 的 nginx 配置问题
【发布时间】:2019-08-17 23:30:34
【问题描述】:

我开始使用 docker 做一个小测试,以便设置我自己的服务器,但我遇到了一些问题。

我使用nginx-fpm 图像,其中包含设置服务器所需的大部分服务。

这是我的Dockerfile 我为了设置基本服务器而做的。我完美地构建了它,没有任何问题,并将其命名为nginx-custom-server

Dockerfile

FROM "richarvey/nginx-php-fpm"

ADD /conf/simple-project.conf /etc/nginx/sites-available/simple-project.conf

RUN mkdir /srv/www/
RUN mkdir /LOGS/
RUN ln -s /etc/nginx/sites-available/simple-project.conf /etc/nginx/sites-enabled/simple-project.conf
RUN rm /etc/nginx/sites-enabled/default.conf

CMD ["/start.sh"]

我通过终端使用以下命令运行它。

docker run --name=server-stack -v /home/ismael/Documentos/docker-nginx/code:/srv/www -v /home/ismael/Documentos/docker-nginx/logs:/LOGS -p 80:80 -d nginx-custom-server:stack

/srv/www 文件夹中,我有一个简单的hello world php。我想在本地机器上更改我的代码,并使用共享文件夹code 将其与 docker 容器同步。

nginx 日志是空的,所以我不知道出了什么问题。我在我的 conf 中设置了日志,但 nginx 没有创建它们,所以我认为我猜一般的 nginx conf 存在问题。

这是我用于我的 hello world 的 conf。我还将此服务器名称映射到主机的主机中。

simple-project.conf

server {
    listen 0.0.0.0:80;
    server_name simple-project.olive.com;
    root /srv/www/simple-project/;

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

    location ~ ^/index\.php(/|$) {
        # the ubuntu default
        fastcgi_pass   /var/run/php-fpm.sock:9000;

        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;

        fastcgi_param APPLICATION_ENV int;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
    }

    location ~ \.php$ {
        return 404;
    }

    error_log /LOGS/custom_error.log;
    access_log /LOGS/custom_access.log;
}

编辑:当我尝试访问 docker 容器内的服务器时出错。

bash-4.4# wget localhost:80 > /tmp/output.html --2019-03-27 12:33:11-- http://localhost/ Resolving localhost... 127.0.0.1, ::1 连接到 localhost|127.0.0.1|:80... 失败:连接被拒绝。连接到 localhost|::1|:80... 失败:地址 无法使用。正在重试。

【问题讨论】:

    标签: docker nginx


    【解决方案1】:

    据我所知,您无法访问服务器有两个原因。

    首先是您不将任何端口从容器转发到主机。您应该在您的 docker run 命令中包含 -p 80:80 参数。

    第二个是你试图监听我认为是容器本身的 IP,它不是静态的(默认情况下)。在 nginx 配置中,您应该将 listen 172.17.0.2:80; 替换为 listen 0.0.0.0:80;

    通过这两项修改,您应该能够访问您的服务器。

    另一种方法(但不推荐)是使用--network=host 参数启动容器。这样,主机的网络实际上在容器内是可见的。在这种情况下,您只需将 nginx 配置设置为侦听有效地址。

    但是,如果问题仍然存在,一个好的方法是在容器运行时运行docker exec -it {$container_id} bash,看看您是否可以从容器本身访问服务器。这意味着服务器运行正常,但由于其他原因,端口未正确转发到主机。

    【讨论】:

    • 感谢您的帮助,但我有一个新问题。我更新了答案,所以提前谢谢。
    • 当你在localhost上有另一个服务监听80端口时,通常会发生错误。这可能是指另一个正在监听80的nginx服务器?找出答案的一种方法是运行 sudo netstat -tlnp | grep 80(在 unix 上),看看哪个是罪魁祸首。
    • 是的,这是真的,我有另一个容器,之前的 nginx 配置。我按照您在回答中所说的进行设置,但我仍然无法访问服务器。我在容器内试图弄清楚发生了什么。我试过这个wget 172.17.0.2:80 > /tmp/output.html,但我从容器内部被拒绝连接。
    • 您是否尝试过从容器内部运行wget localhost:80?由于服务器在 0.0.0.0 上,您肯定不会从 in 容器中收到来自 172.17.0.2 的任何答复。
    • 我更新了问题,但它也给了我一个连接被拒绝的错误。
    猜你喜欢
    • 2022-01-09
    • 2021-11-29
    • 2017-01-09
    • 1970-01-01
    • 2014-06-03
    • 2016-10-13
    • 2019-09-24
    • 2017-12-29
    相关资源
    最近更新 更多