欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

docker部署spring boot项目,配置Nginx负载均衡

程序员文章站 2022-06-13 16:05:28
...

1.配置项目端口8081,把项目打成jar包fund-api.jar

2.把包复制到/var/apps/fund-api

3.在/var/apps/fund-api下创建文件Dockerfile

FROM java:8

ARG JAVA_OPTS="-Xms256m -Xmx256m"

ADD fund-api.jar fund-api.jar
EXPOSE 8081
#设置时区
RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
ENTRYPOINT java $JAVA_OPTS -jar /fund-api.jar

4.用包fund-api.jar和Dockerfile创建3个镜像和3个容器,并运行容器

cd /var/apps/fund-api
docker build -t fund-api-1 .
docker run -d -v /var/apps/fund-api/1/logs/:/logs/ -p 8081:8081  fund-api-1

docker build -t fund-api-2 .
docker run -d -v /var/apps/fund-api/2/logs/:/logs/ -p 8082:8081  fund-api-2

docker build -t fund-api-3 .
docker run -d -v /var/apps/fund-api/3/logs/:/logs/ -p 8083:8081  fund-api-3

5.配置Nginx负载均衡

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
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;
	#应用部署在3个地方
    upstream tomcatserver1 {  
        server 106.55.172.84:8081;
        server 106.55.172.84:8082;
        server 106.55.172.84:8083;
    }
    server {
        listen 80; # 监听80端口
        location / {
            proxy_pass   http://tomcatserver1; # 应用服务器HTTP地址
        }
    }
}

6.运行Nginx容器

sudo docker run -d -p 9000:80 --name nginx-web -v ~/nginx/www:/usr/share/nginx/html -v ~/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -v ~/nginx/logs:/var/log/nginx nginx