Docker安装Nginx
现阶段主要目的是做一些静态资源路径的转发代理,相当于一个web服务器,tomcat也可以设置凡访问静态资源。但考虑到后续还需要作为代理服务器对域名等进行代理转发,所以使用nginx。
准备好要挂载的nginx配置目录
mkdir -p /mydata/nginx/conf
启动临时nginx容器用于拷贝文件
docker run -p 80:80 --name nginx -d nginx
拷贝出 Nginx 容器的配置
# 将nginx容器中的nginx目录复制到本机的/mydata/nginx/conf目录
docker container cp nginx:/etc/nginx /mydata/nginx/conf# 复制的是nginx目录,将该目录的所有文件移动到 conf 目录
mv /mydata/nginx/conf/nginx/* /mydata/nginx/conf/# 删除多余的 /mydata/nginx/conf/nginx目录
rm -rf /mydata/nginx/conf/nginx
删除临时容器
docker rm nginx -f
启动nginx容器
docker run -p 80:80 --name nginx \
-v /mydata/nginx/html:/usr/share/nginx/html \
-v /mydata/nginx/logs:/var/log/nginx \
-v /mydata/nginx/conf/:/etc/nginx \
-d nginx
设置自启动
docker update nginx --restart=always
测试nginx
echo '<h1>nginx sucess</a></h1>' \
>/mydata/nginx/html/index.html
访问http://服务器ip。如下表示nginx成功。
Nginx配置
nginx配置文件介绍(网图)
配置文件/mydata/nginx/conf/nginx.conf
可以看到,在 http 块中最后有 include /etc/nginx/conf.d/*.conf; 这句配置说明在 conf.d 目录下所有 .conf 后缀的文件内容都会作为 nginx 配置文件 http 块中的配置。
这是为了防止主配置文件太复杂,也可以对不同的配置进行分类。
user nginx;
worker_processes auto;error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
我们可以在/mydata/nginx/conf/conf.d/下新建自定义的配置文件,具体可以参考default.conf
nginx配置反向代理 80端口到tomcat8080端口
server {listen 80;listen [::]:80;server_name 121.41.225.xxx; #域名或者IP地址;#access_log /var/log/nginx/host.access.log main;location / {root /usr/share/nginx/html;index index.html index.htm;proxy_pass http://121.41.225.xxx:8080/; #当你访问80端口可以实现向8080端口转发}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html#error_page 500 502 503 504 /50x.html;location = /50x.html {root /usr/share/nginx/html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {# proxy_pass http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {# root html;# fastcgi_pass 127.0.0.1:9000;# fastcgi_index index.php;# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;# include fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {# deny all;#}
}
nginx访问静态资源配置
静态资源都放在nginx/html/static下
设置 /static/ 下所有的请求都转给 nginx
location /static/ {
root /user/share/nginx/html;
}
访问资源测试,成功: