Docker安装Nginx,配置宿主机和容器的工作目录挂载和多个端口监听实例

1. 创建目录

mkdir -p /opt/nginx/conf
mkdir -p /opt/nginx/html

2. 创建配置文件

touch /opt/nginx/conf/nginx.conf

在nginx.conf文件添加如下配置,多个端口监听

worker_processes  1;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen     80;
        server_name  localhost;

        location / {
            root /usr/share/nginx/html; # nginx工作目录是容器的而非宿主机
            index index.html index.htm;
	}
        # 代理转发请求至网关,prod-api标识解决跨域问题
	location /prod-api/ {
            proxy_pass http://www.youlai.store:9999/;
        }
    }

    server {
        listen     9000;
        server_name localhost;
        location / {
             root  /usr/share/nginx/html; # nginx工作目录是容器的而非宿主机
             index index.html index.htm;
        }
        # axios 配置代理转发 解决浏览器禁止跨域
        location /prod-api/ {
             proxy_pass http://www.youlai.store:9999/;
        }
    }
}

3. 拉取镜像

docker pull nginx

查看镜像

docker images

4. 创建容器并启动

docker run -it -d \
--name nginx \
-p 80:80 \
-p 9000:9000\
-v /opt/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /opt/nginx/html:/usr/share/nginx/html \
nginx 

参数-v 表示挂载文件或目录,左边为宿主机位置,右边为容器位置,这样在宿主机修改的文件或目录会自动到容器内。如果不做配置文件的同步,宿主机修改的配置文件在容器无法生效;如果不做目录的挂载,通过nginx访问的资源会报404。

5. 查看容器

docker ps -a

6. 查看nginx启动日志

docker logs nginx

7. 启动、关闭、重启nginx

docker start nginx
docker stop nginx
docker restart nginx
posted @ 2020-08-31 19:43  有来技术  阅读(3137)  评论(0编辑  收藏  举报