docker配置nginx环境

2022-04-05  本文已影响0人  冲鸭_程序猿

拉取nginx镜像

docker pull nginx:1.20.2

创建映射文件

# 配置文件路径
mkdir -p /data/nginx/conf/conf.d
# 静态资源路径
mkdir -p /data/nginx/html
# 日志文件路径
mkdir -p /data/nginx/logs

拷贝默认配置

# 启动容器
docker run -d --name nginx -p 80:80 nginx
# 获取容器 ID
docker ps 
# 拷贝配置文件,383881afbd49 为上一步查到的容器 ID
docker cp 383881afbd49:/etc/nginx/nginx.conf /data/nginx/conf/nginx.conf
docker cp 383881afbd49:/etc/nginx/conf.d /data/nginx/conf
docker cp 383881afbd49:/usr/share/nginx/html /data/nginx/html
# 删除容器
docker stop 383881afbd49
docker rm  383881afbd49

自定义配置文件

在 data/nginx/conf/conf.d创建自定义nginx配置文件,本例子以nacos集群配置为例。

# 复制data/nginx/conf/conf.d/default.conf文件 到当前目录下的nacos_80.conf
cp default.conf ./nacos_80.conf
image.png

修改nacos_80.conf配置文件

# 负载均衡配置 注意名称不能包含下划线
upstream nacosCluster {
   server 120.48.21.24:8848;
   server 121.4.53.209:8848;
}

server {
    listen       80;
    server_name  120.48.21.24;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        add_header backendIP $upstream_addr;  # 添加http响应头,以便知道负载到哪台服务器上了
        add_header backendCode $upstream_status; # 响应码
        proxy_pass http://nacosCluster;  # 代理转发到cluster
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

启动容器,并挂载文件

docker run -d -p 80:80 --name nginx --restart=always -v /data/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -v /data/nginx/conf/conf.d:/etc/nginx/conf.d -v /data/nginx/html:/usr/share/nginx/html -v /data/nginx/logs:/var/log/nginx nginx:1.20.2
上一篇下一篇

猜你喜欢

热点阅读