Skip to content

Instantly share code, notes, and snippets.

@katzefudder
Last active August 19, 2022 17:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katzefudder/a244bd2123838ec8a0cc87b6b942f299 to your computer and use it in GitHub Desktop.
Save katzefudder/a244bd2123838ec8a0cc87b6b942f299 to your computer and use it in GitHub Desktop.
A simple openresty proxy with metrics endpoint
FROM openresty/openresty:1.21.4.1-1-alpine
ENV PATH=$PATH:/usr/local/openresty/luajit/bin:/usr/local/openresty/nginx/sbin:/usr/local/openresty/bin
RUN apk update \
&& apk add curl perl \
# install nginx-lua-openresty https://opm.openresty.org/package/knyar/nginx-lua-prometheus/
&& opm get knyar/nginx-lua-prometheus \
&& mkdir -p /var/log/nginx \
&& mkdir /var/www \
# clean up nginx default config
&& rm /etc/nginx/conf.d/default.conf \
&& apk del curl perl \
&& rm -rf /var/cache/apk/*
COPY nginx.conf /usr/local/openresty/nginx/conf
COPY prometheus.conf /etc/nginx
COPY proxy.conf /etc/nginx/conf.d
EXPOSE 8080
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
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;
error_log /var/log/nginx/error.log warn;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
gzip on;
include /etc/nginx/prometheus.conf;
include /etc/nginx/conf.d/*.conf;
}
lua_package_cpath "$prefix/resty_modules/lualib/?.so;;";
lua_package_path '/usr/local/openresty/site/lualib/?.lua;;';
lua_shared_dict prometheus_metrics 10M;
init_worker_by_lua_block {
prometheus = require("prometheus").init("prometheus_metrics")
metric_requests = prometheus:counter(
"nginx_http_requests_total", "Number of HTTP requests", {"host", "status"})
metric_latency = prometheus:histogram(
"nginx_http_request_duration_seconds", "HTTP request latency", {"host"})
metric_connections = prometheus:gauge(
"nginx_http_connections", "Number of HTTP connections", {"state"})
}
log_by_lua_block {
metric_requests:inc(1, {ngx.var.server_name, ngx.var.status})
metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name})
}
server {
listen 8080;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
index index.html;
location / {
proxy_pass http://localhost:80/;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /nginx_status {
stub_status;
}
location /metrics {
content_by_lua '
metric_connections:set(ngx.var.connections_reading, {"reading"})
metric_connections:set(ngx.var.connections_waiting, {"waiting"})
metric_connections:set(ngx.var.connections_writing, {"writing"})
prometheus:collect()
';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment