1.创建挂载目录

mkdir /opt/nginx/conf
mkdir /opt/nginx/log
mkdir /opt/nginx/html

2.拉取nginx镜像

#默认拉取的是nginx最新版本
docker pull nginx

3.启动nginx容器

docker run --restart=always --name=nginx -it -p 80:80 
-v /opt/nginx/conf/conf.d:/etc/nginx/conf.d 
-v /opt/nginx/conf/nginx.conf:/etc/nginx/nginx.conf 
-v /opt/nginx/log:/var/log/nginx 
-v /opt/nginx/html:/usr/share/nginx/html 
-d nginx:latest

挂载目录说明:

命令描述
-v /opt/nginx/conf/conf.d:/etc/nginx/conf.d挂载该路径下的nginx配置文件
-v /opt/nginx/conf/nginx.conf:/etc/nginx/nginx.conf挂载nginx.conf配置文件
-v /opt/nginx/log:/var/log/nginx挂载nginx日志文件
-v /opt/nginx/html:/usr/share/nginx/html挂载nginx内容

2.访问nginx主页

在浏览器访问nginx主页http://ip:80,但是网页显示404.NotFound
查看/opt/nginx/log目录下error.log日志文件,显示

“/etc/nginx/html/index.html” is not found (2: No such file or directory)

在这里插入图片描述

进入运行的nginx容器:

docker exec -it 容器ID /bin/bash

在容器内进入/etc/nginx目录下,创建html文件夹:mkdir html
在html目录下创建index.html文件:touch index.html
index.html内容如下:

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome to nginx!</title>
    <style>
      html { color-scheme: light dark; }
      body { width: 35em; margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif; }
    </style>
  </head>
  <body>
    <h1>Welcome to nginx!</h1>
    <p>If you see this page, the nginx web server is successfully installed and
      working. Further configuration is required.</p>

    <p>For online documentation and support please refer to
      <a href="http://nginx.org/">nginx.org</a>.<br/>
      Commercial support is available at
      <a href="http://nginx.com/">nginx.com</a>.</p>

    <p><em>Thank you for using nginx.</em></p>
  </body>
</html>

再次在浏览器访问nginx主页,网页正常显示
在这里插入图片描述

3.nginx的配置

在/opt/nginx/conf下新建配置文件nginx.conf,文件内容如下

user  root;
worker_processes  1;

events {
  worker_connections  1024;
}


http {
  include       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  logs/access.log  main;

  sendfile        on;
  #tcp_nopush     on;

  #keepalive_timeout  0;
  keepalive_timeout  65;


  include ./conf.d/*.conf;
}

include ./conf.d/*.conf指包含/opt/nginx/conf/conf.d/目录下所有的配置文件
所以在/opt/nginx/conf/conf.d目录下新建适用于自己服务的conf配置文件
注 : 配 置 文 件 中 不 要 用 l o c a l h o s t , 而 是 用 服 务 器 i p 代 替 l o c a l h o s t \color{red}{注:配置文件中不要用localhost,而是用服务器ip代替localhost} localhostiplocalhost

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐