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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM