openresty redis all in one docker demo
一个简单的docker demo 集成openresty+ redis,可以实现基于redis的动态修改反向代理的处理
环境准备
- docker-compose 文件
version: "3"
services:
nginx-redis:
build: ./
image: dalongrong/appdemorong
tty: true
ports:
- "6379:6379"
- "8099:80"
- dockerfile
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"]
- redis.conf 配置文件
很简单主要是使用后台任务运行,同时禁用保护模式,添加以下内容就可以了
daemonize yes
protected-mode no
- nginx.conf
基于redis 的host 查找,实现动态负载(需要手工修改redis key 信息)
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;
}
}
}
- entrypoint.sh
很简单就是启动redis以及openresty
#!/bin/bash
redis-server /redis.conf
exec /usr/local/openresty/bin/openresty -g "daemon off;"
运行&&测试
- 构建&&启动
docker-compose build && docker-compose up -d
- 添加负载均衡配置
- 访问效果
当前是一个jenkins 界面
重新修改为一个git的界面
说明
demo 很简单,主要是为了运行一个测试环境,但是同时为了方便进行反向代理后端的调整,所以写了一个简单的demo
实际上更好的方式可能是使用supervisor,tini,或者docker 自带的init 功能
tini 参考dockerfile 如下:
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"]