先看下容器規划:

上圖中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;
}
}
參考文章:
