docker学习(6) docker中搭建java服务及nginx反向代理

先看下容器规划:

上图中mysql容器的搭建见上篇博客,service1/2为java rest service,创建脚本如下:

docker run -d -h service1 \
  -v /Users/yjmyzz/data/service:/opt/service \
  --name service1 \
  --link mysql:mysql -p 0.0.0.0:9081:8080 java \
  java -jar opt/service/spring-boot-rest-framework-1.0.0.jar

docker run -d -h service2 \
  -v /Users/yjmyzz/data/service:/opt/service \
  --name service2 \
  --link mysql:mysql -p 0.0.0.0:9082:8080 java \
  java -jar opt/service/spring-boot-rest-framework-1.0.0.jar  

注:对外的端口映射可选,因为最后会用nginx转发,暴露出来是为了方便单独测试service1及service2是否正常。

nginx容器的创建脚本如下:

docker run -d -h nginx1 \
  -v /Users/yjmyzz/data/nginx/html:/usr/share/nginx/html:ro \
  -v /Users/yjmyzz/data/nginx/conf/nginx.conf:/etc/nginx/nginx.conf:ro \
  -v /Users/yjmyzz/data/nginx/conf/conf.d:/etc/nginx/conf.d:ro \
  -p 0.0.0.0:9000:80 \
  --link service1:service1 \
  --link service2:service2 \
  --name nginx1 nginx

注:因为nginx1要访问service1/2,所以用了二个link来打通nginx1到service1/2的网络访问,另外有3个-v参数,分别用于映射静态资源、主配置文件、虚拟主机映射文件,最后将80端口映射到mac本机9000端口。

~/data/nginx/conf/nginx.conf参考配置如下:

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;
}

~/data/nginx/conf/conf.d/default.conf参考配置如下:

proxy_connect_timeout 5;

upstream service_group{
      server service1:8080 max_fails=1 fail_timeout=60s;
      server service2:8080 max_fails=1 fail_timeout=60s;
      ip_hash;
}

server {
    listen       80;
    server_name  localhost;
    #root /usr/share/nginx/html;
    #index index.html index.htm;

    location / {
	 proxy_next_upstream http_502 http_504 error timeout invalid_header;
         proxy_pass http://service_group ;
         proxy_set_header X-Forwarded-For $remote_addr;
    }

    location ~ .*\.(js|css)?$ {
         expires 1h;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

参考文章:

docker-nginx镜像使用文档

docker-java镜像使用文档

posted @ 2016-02-02 10:13  菩提树下的杨过  阅读(5642)  评论(0编辑  收藏  举报