简简单单---docker上安装nginx

1、拉去nginx

$ docker pull nginx

2、启动nginx

$ docker run --name nginx -d -p 80:80 --restart=always nginx:latest

3、 访问nginx

4、挂载nginx

为了方便我们发布静态资源和修改nginx配置文件。所以需要把镜像nginx关键文件挂载到主机目录,这样就不需要登录到镜像nginx去修改配置。
使用docker exec -it nginx bash命令可以登录到我们启动的nginx容器里面,从/etc/nginx/nginx.conf文件可以看到nginx的配置文件、日志和静态资源位置,我们把这些文件拷贝到主机。

#进入/data文件夹创建nginx目录
$ cd /data
$ mkdir nginx
$ cd nginx
#复制nginx容器目录到主机
$ docker cp nginx:/etc/nginx/nginx.conf nginx.conf
$ docker cp nginx:/etc/nginx/conf.d conf.d
$ docker cp nginx:/usr/share/nginx/html html
$ docker cp nginx:/var/log/nginx log

5、配置nginx.conf

# user root;
worker_processes 8;

events {
    worker_connections  10240;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$host "$request" $remote_addr $remote_user [$time_local] $status $request_time $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main; 
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    send_timeout 300;

    client_max_body_size 200m;
    sendfile        on;
    #tcp_nopush     on;
    #gzip  on;

    limit_req_zone $binary_remote_addr zone=req_limit_per_ip_second:1m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=req_limit_per_ip_minute:10m rate=100r/s;

    #server配置
        server{
        listen 80;
        server_name 127.0.0.1;
        
        location ~ .*\.(php|php5|jsp)$ {
            deny all;
        }

        location / {
            root   /usr/share/nginx/html; 
            index  index.html index.htm;
        }
    }

}

6、重新挂载nginx

$ docker run --name nginx-d -p 80:80 --restart=always -e TZ="Asia/Shanghai" -v /data/nginx/html:/usr/share/nginx/html -v  /data/nginx/log:/var/log/nginx -v  /data/nginx/nginx.conf:/etc/nginx/nginx.conf:ro nginx:latest
参数解析:
-d 		后台运行容器,并返回容器ID;
--name       	为容器起一个容易区分且容易书写的名字
-p           	映射宿主机端口到容器端口,宿主机端口:容器端口
--restart=always  机器重启时自动启动容器
-e       	设定一些必须的环境变量。
-e TZ="Asia/Shanghai" 设定时区为上海,强烈建议国内设定,否则容器内打印的所有日志时间都会差8小时。
-v  		挂载宿主机文件到容器。

7、修改html验证nginx挂载

#修改index.html,然后重启nginx
$ vim index.html
$ docker restart nginx

8、参考

https://www.cnblogs.com/jying/p/12182715.html

posted @ 2022-05-01 14:01  孙振光  阅读(174)  评论(0编辑  收藏  举报