一、准备环境
1、搜索并下载nginx版本
sudo docker search nginx
可看到如图所示
这里选择官方最新版本下载
sudo docker pull nginx:latest
2、查看nginx镜像
sudo docker images
3、新建nginx配置存放目录
mkdir -p nginx/data
mkdir -p nginx/config
mkdir -p nginx/logs
mkdir -p nginx/ssl
二、安装并验证nginx
1、执行安装命令
其中--name nginx-test
表示容器名称设为nginx-test;
-p 8080:80
端口进行映射,将本地 8080 端口映射到容器内部的 80 端口;
-v
将宿主的目录/文件映射到docker容器内部目录/文件:rw
读写权限;
-d nginx
设置容器在在后台一直运行;
–restart=always
运行容器时使用–restart参数可以指定一个restart策略,来指示在退出时容器应该如何重启或不应该重启。
no – 容器退出时不要自动重启。这个是默认值。
on-failure[:max-retries] – 只在容器以非0状态码退出时重启。可选的,可以退出docker daemon尝试重启容器的次数。
always – 不管退出状态码是什么始终重启容器。当指定always时,docker daemon将无限次数地重启容器。容器也会在daemon启动时尝试重启,不管容器当时的状态如何。
unless-stopped – 不管退出状态码是什么始终重启容器,不过当daemon启动时,如果容器之前已经为停止状态,不要尝试启动它。
docker run \
--name nginx-test \
--restart=always \
-p 8081:8081 \
-p 8082:8082 \
-v /home/centos/nginx/data/html:/usr/share/nginx/html \
-v /home/centos/nginx/config/nginx.conf:/etc/nginx/nginx.conf \
-v /home/centos/nginx/conf.d:/etc/nginx/conf.d \
-v /home/centos/nginx/config/conf.d/default.conf:/etc/nginx/conf.d/default.conf \
-v /home/centos/nginx/logs:/var/log/nginx \
-v /home/centos/nginx/ssl/:/ssl/ \
-d \
nginx
a)出现异常
docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:545: container init caused: rootfs_linux.go:76: mounting "/home/centos/nginx/config/nginx.conf" to rootfs at "/etc/nginx/nginx.conf" caused: mount through procfd: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type.
原因:不支持直接挂载文件,只能挂载文件夹,要么将文件提前建好,要么先不挂在文件,等容器建好之后将配置文件取出来,放到映射目录中
b)异常解决
在宿主服务器/home/centos/nginx/config/
目录下放入默认的nginx.conf文件,重新删除原容器,重新运行安装容器,问题解决。
2、验证
通过浏览器访问http://ip:port/
a)查看日志
在宿主主机/home/centos/nginx/logs
下的error.log里能看到
原来是首页路径不对。
b)修改nginx.conf配置
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
c)重启nginx之后重新访问
未赋权,进入nginx容器目录/usr/share/nginx
执行命令chmod -R 777 html
重新访问,成功。