一個簡單的docker demo 集成openresty+ redis,能夠實現基於redis的動態修改反向代理的處理html
version: "3" services: nginx-redis: build: ./ image: dalongrong/appdemorong tty: true ports: - "6379:6379" - "8099:80"
FROM openresty/openresty:alpine RUN apk add --update \ && apk add redis ADD entrypoint.sh /entrypoint.sh COPY redis.conf /redis.conf COPY nginx.conf usr/local/openresty/nginx/conf/ ENV PATH=$PATH:/usr/bin EXPOSE 6379 EXPOSE 80 ENTRYPOINT ["sh", "/entrypoint.sh"]
daemonize yes protected-mode no
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; gzip on; resolver 114.114.114.114; real_ip_header X-Forwarded-For; real_ip_recursive on; server { listen 80; server_name localhost; charset utf-8; location / { set $subdomain api.yonyou.com; access_by_lua_block { local redis = require "resty.redis" local red = redis:new() red:set_timeout(1000) local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end local host = ngx.var.host; local res, err = red:get(host) ngx.var.subdomain = res } proxy_pass http://$subdomain/$uri; proxy_set_header Host $subdomain; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /ip { default_type text/html; content_by_lua_block{ ngx.say(ngx.var.remote_addr) } } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
#!/bin/bash redis-server /redis.conf exec /usr/local/openresty/bin/openresty -g "daemon off;"
docker-compose build && docker-compose up -d
demo 很簡單,主要是爲了運行一個測試環境,可是同時爲了方便進行反向代理後端的調整,因此寫了一個簡單的demo
實際上更好的方式多是使用supervisor,tini,或者docker 自帶的init 功能
tini 參考dockerfile 以下:nginx
FROM openresty/openresty:alpine ENV TINI_VERSION v0.18.0 RUN apk add --update \ && apk add redis \ && apk add --no-cache tini ADD entrypoint.sh /entrypoint.sh COPY redis.conf /redis.conf COPY nginx.conf usr/local/openresty/nginx/conf/ ENV PATH=$PATH:/usr/bin EXPOSE 6379 EXPOSE 80 ENTRYPOINT ["/sbin/tini","-s", "--", "/entrypoint.sh"]