nginx:[emerg]在/etc/nginx/conf.d/default.conf:1中不允许使用“ http”指令

时间:2019-06-10 13:14:36

标签: docker nginx

我正在尝试使用nginx和docker-compose设置服务器,但是每次尝试“ docker-compose up”时都会出现这些错误:

webserver | 2019/06/10 13:04:16 [emerg] 1#1: "http" directive is not allowed here in /etc/nginx/conf.d/default.conf:1
webserver | nginx: [emerg] "http" directive is not allowed here in /etc/nginx/conf.d/default.conf:1

我尝试用html {}包装所有内容,删除服务器{},而不是80的另一个端口...

nginx Dockerfile

FROM nginx

COPY default.conf /etc/nginx/conf.d/default.conf

default.conf

server {
    listen       80;
    server_name  localhost;

    location / {
        proxy_set_header  Host $host;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_pass http://app:8080/;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

3 个答案:

答案 0 :(得分:0)

通过覆盖nginx.conf解决了这个问题。

Dockerfile

FROM nginx

COPY default.conf /etc/nginx/conf.d/default.conf

default.conf

worker_processes 1;

events { worker_connections 1024; }

http {

    sendfile on;

    upstream app {
        server app:8080;
    }

    server {
        listen 8080;

        location / {
            proxy_pass         http://app;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }

}

答案 1 :(得分:0)

当您尝试覆盖默认的Nginx配置文件时会发生这种情况,该文件不接受某些httpuser之类的根属性。如果您需要这些额外的配置,可以尝试将必须复制的内容复制到/etc/nginx/nginx.conf

因此,代替此:COPY default.conf /etc/nginx/conf.d/default.conf

执行此操作:COPY nginx.conf /etc/nginx/nginx.conf

注意:通过复制到/etc/nginx/conf.d/,您将覆盖默认配置。

答案 2 :(得分:0)

我想为上面提出的解决方案添加另一个解决方案。如上所述,替换 nginx.confdefault.conf 有效。我在 docker-compose.yml 完成:

    volumes:
      - ./services/nginx.conf:/etc/nginx/nginx.conf

然而,我在我的 nginx.conf 文件中遇到了使用环境变量的必要性,这需要在 /etc/nginx/templates/ 中创建一个模板, envsubst 然后在 /etc/nginx/conf.d 中输出,就像解释的 here 一样。

我遇到了以下错误:

  • nginx: [emerg] "events" directive is not allowed here in /etc/nginx/conf.d/default.conf
  • nginx: [emerg] "http" directive is not allowed here in /etc/nginx/conf.d/default.conf

这是 nginx.conf 文件的工作解决方案(文件名在这里无关紧要,因为它在复制到容器时发生了更改,请参阅下面的 docker-compose,但我喜欢将其命名为 nginx.conf清晰):

server {
  listen ${FE_PORT};
  location / {
    proxy_pass http://frontend:${FE_PORT};
  }
}
server {
  listen ${BE_PORT};
  location / {
    proxy_pass http://backend:${BE_PORT};
  }
}
server {
  listen ${SERVICE_PORT};
  location / {
    proxy_pass http://service:${SERVICE_PORT};
  }
}

还有docker-compose.yml

nginx:
    image: nginx
    container_name: nginx
    ports:
      - "${FE_PORT}:${FE_PORT}"
      - "${BE_PORT}:${BE_PORT}"
      - "${SERVICE_PORT}:${SERVICE_PORT}"
    environment:
      - FE_PORT
      - BE_PORT
      - SERVICE_PORT
    volumes:
      - ./nginx.conf:/etc/nginx/templates/default.conf.template