查找镜像
docker search nginx
拉取镜像
docker pull nginx
如果需要指定版本。按照如下写法
docker pull nginx:替换为你的版本号
建立nginx镜像
docker run -d -p 80:80 \
--name nginx --net host \
-v /docker/nginx/www:/usr/share/nginx/html \
-v /docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /docker/nginx/logs:/var/log/nginx \
nginx
释义
-d 后台运行
-p 主机映射端口:容器映射端口
--name 容器名称
-v 数据挂载卷。主机映射文件位置:容器映射文件位置
nginx 此处为你拉取的镜像。如需指定版本按如下格式nginx:1.0,不指定为最新版本
运行上方可能会报如下错误
docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/docker/nginx/conf/nginx.conf" to rootfs at "/etc/nginx/nginx.conf": mount /docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf (via /proc/self/fd/6), flags: 0x5000: 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.
上述报错参考如下文章得到解决,亲测可用
(关于:docker容器启动nginx》Error response from daemon: OCI runtime create failed-CSDN博客)
下方记录一下
- 先删掉刚创建的镜像
docker rm -f nginx - 删除刚刚创建镜像产生的文件夹
rm -rf /opt/nginx/conf/nginx.conf - 执行如下命令
docker run -d -p 8081:80 \
--name nginx --net host \
-v /opt/nginx/www:/usr/share/nginx/html \
-v /opt/nginx/logs:/var/log/nginx nginx
- 进入创建好的容器,确认配置文件位置,进入文件夹后应该能看到nginx.conf文件
docker exec -it nginx /bin/bash
cd /etc/nginx/
- 退出容器,进入创建的配置文件夹。从容器中复制配置文件到宿主机中
exit
cd /opt/nginx/conf/
docker cp nginx:/etc/nginx/nginx.conf ./
ls #查看配置文件是否成功复制到宿主机下
文件复制成功返回
- 配置文件复制成功后,删除当前镜像
docker rm -f nginx
- 重新创建nginx镜像
docker run -d -p 80:80 \
--name nginx \
--net host \
-v /opt/nginx/www:/usr/share/nginx/html \
-v /opt/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /opt/nginx/logs:/var/log/nginx \
nginx
创建如上容器可能会报如下警告,端口号没有映射上。此处是因为docker启动时指定--network=host或-net=host,如果还指定了-p或-P,那这个时候就会有此警告,并且通过-p或-P设置的参数将不会起到任何作用,端口号会以主机端口号为主,重复时则递增。此处将--net host改为--net bridge模式即可
docker run -d -p 80:80 \
--name nginx \
--net bridge \
-v /opt/nginx/www:/usr/share/nginx/html \
-v /opt/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /opt/nginx/logs:/var/log/nginx \
nginx
nginx容器创建完成
主机ip:80 访问nginx主页,此处访问可能会报403,原因为www文件夹下没有index.html页面
解决办法
下载nginx的index.html页面后将文件放入/opt/nginx/www文件夹下,再次访问可成功