安装nginx并挂载
1.查看可用版本:
docker search nginx
2.拉取官方的最新版本的镜像:
docker pull nginx:latest
3.查看本地镜像
使用以下命令来查看是否已安装了 nginx:
docker images
4.在主机创建挂载目录
mkdir -p /home/nginx/conf
mkdir -p /home/nginx/html
mkdir -p /home/nginx/logs
5.创建配置文件/home/nginx/conf/nginx.conf
文件内容如下:
user nginx; #设置nginx服务的系统使用用户
worker_processes 1; #工作进程数
error_log /etc/nginx/logs/error.log warn; #nginx的错误日志
pid /etc/nginx/nginx.pid; #nginx启动时候的pid
events {
worker_connections 1024; #每个进程允许的最大连接数
}
http { #http请求配置,一个http可以包含多个server
#定义 Content-Type
include /etc/nginx/mime.types;
default_type application/octet-stream;
#访问日志,记录到access.log中
access_log /etc/nginx/logs/access.log;
#nginx的一大优势,高效率文件传输
sendfile on;
#tcp_nopush on;
#客户端与服务端的超时时间,单位秒
keepalive_timeout 65;
#gzip on;
server { #http服务,一个server可以配置多个location
listen 80; #服务监听端口
server_name localhost; #主机名、域名
location / {
root /etc/nginx/html; #页面存放目录
index index.html index.htm; #默认页面
}
#error_page 404 /404.html;
# 将500 502 503 504的错误页面重定向到 /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html { #匹配error_page指定的页面路径
root /etc/nginx/html; #页面存放的目录
}
}
include /etc/nginx/conf.d/*.conf;
}
6.运行容器并把nginx容器的配置文件挂载到主机
// 运行容器并挂载命令
docker run --name nginx-test -d -p 80:80 --restart=always --privileged=true -v /home/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -v /home/nginx/html:/etc/nginx/html -v /home/nginx/logs:/etc/nginx/logs nginx
说明:
// 运行容器并挂载命令
docker run --name nginx-test //容器起名为nginx-test
-d //后台运行
-p 80:80 //把主机80端口映射到容器80端口
--restart=always
--privileged=true //防止挂载时权限不够
-v /home/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
-v /home/nginx/html:/etc/nginx/html
-v /home/nginx/logs:/etc/nginx/logs
//把文件挂载到主机目,主机文件目录:容器文件目录
nginx //运行镜像的名称
7.运行nginx,查看是否在运行中
# 启动容器
docker start nginx-test
# 查看运行中的容器
docker ps
8.浏览器打开 ip:port
备注:此时,主机中的/home/nginx/html已经挂载到nginx的web路径,在此路径中创建页面可以直接被访问到。