一、拉取nginx官方鏡像,鏡像更多解釋
1、登錄docker 鏡像官網搜索nginx,找到制定的版本拉去,這里使用默認最新nginx版本。
docker pull nginx:latest
2、查看docker的鏡像
docker images
二、啟動docker應用
1、簡單啟動,命令弊端,nginx需要取單獨修改配置文件和查看nginx打印日志,所以不建議使用這種方式,推薦使用第二種方式
## 構建container docker run -d --name nginx -p 80:80 nginx ## 啟動,執行后就可以訪問了http://localhost/ docker start nginx
2、推薦啟動方式,修改配置可以持久化和查看日志
第一步、首先創建nginx在本地映射目錄。www用於映射靜態文件,logs存儲日志,conf存在nginx配置信息,conf.d統一配置服務監聽信息
mkdir -p /root/nginx/www /root/nginx/logs /root/nginx/conf /root/nginx/conf/conf.d
第二步、創建使用的文件
touch /root/nginx/conf/conf.d/default.conf /root/nginx/conf/nginx.conf /root/nginx/www/index.xml
在default.conf文件中插入一下內容,容器內部的路徑/etc/nginx/conf.d/

server { listen 80; server_name localhost; #charset koi8-r; #access_log /var/log/nginx/host.access.log main; location / { root /usr/share/nginx/html; index index.html index.htm; } #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; #} }
配置 nginx.conf 文件中插入一下內容,容器內部路徑/etc/nginx

user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; }
配置index.html

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Docker Nginx</title> </head> <body> <h1>標題: Docker Nginx</h1> <p>內容: Hello, Nginx.</p> </body> </html>
第三步、構建nginx啟動鏡像並且啟動
docker run -d -p 80:80 --name nginx -v /root/nginx/www:/usr/share/nginx/html -v /root/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -v /root/nginx/conf/conf.d:/etc/nginx/conf.d -v /root/nginx/logs:/var/log/nginx nginx
命令說明:
- -d 容器進入后端運行
- -p 80:80: 將主機的 80 端口 映射到 容器的 80 端口
- --name nginx:將容器命名為 nginx
- -v /root/nginx/www:/usr/share/nginx/html:將我們自己創建的 www 目錄掛載到容器的 /usr/share/nginx/html
- -v /root/nginx/conf/nginx.conf:/etc/nginx/nginx.conf:將我們自己創建的 nginx.conf 掛載到容器的 /etc/nginx/nginx.conf
- -v /root/nginx/logs:/var/log/nginx:將我們自己創建的 logs 掛載到容器的 /var/log/nginx
- -v /root/nginx/conf/conf.d:/etc/nginx/conf.d:將我們自己創建的 logs 掛載到容器的 /etc/nginx/conf.d
啟動nginx
docker start nginx
第三步訪問http://localhost/
更過配置nginx.conf Nginx 服務器安裝及配置文件詳解