Last active
January 13, 2016 11:02
-
-
Save terion-name/816f3e37d5392a810d5a to your computer and use it in GitHub Desktop.
nginx config for resolving docker containers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo "www-data ALL=(ALL:ALL) NOPASSWD:/usr/bin/docker inspect *" >> /etc/sudoers |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
server { | |
listen *; | |
server_name {{host}}; | |
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; | |
set $attempt 0; | |
location / { | |
try_files '/dev/null' @run; | |
} | |
location @run { | |
internal; | |
set $container_name "{{container_name}}"; | |
set $upstream ""; | |
rewrite_by_lua ' | |
local attempt = tonumber(ngx.var.attempt) | |
if attempt > 1 then | |
ngx.log(ngx.ALERT, "Upstream down") | |
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) | |
end | |
local routes = ngx.shared.upstream_cache | |
if attempt > 0 then | |
ngx.log(ngx.ALERT, "Deleteing cache") | |
routes:delete(ngx.var.http_host) | |
end | |
ngx.var.attempt = attempt + 1 | |
-- try cached route first | |
local route = routes:get(ngx.var.http_host) | |
if route == nil then | |
ngx.log(ngx.ALERT, "Asking docker about IP of " .. ngx.var.http_host) | |
local handle = io.popen("sudo /usr/bin/docker inspect --format \'{{ .NetworkSettings.IPAddress }}\' " .. ngx.var.container_name) | |
local result = handle:read("*a") | |
handle:close() | |
if (result == nil or result == "") then | |
routes:delete(ngx.var.http_host) | |
ngx.log(ngx.ALERT, "Got empty IP, exiting") | |
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) | |
else | |
ngx.log(ngx.ALERT, "Got IP " .. result) | |
route = result | |
end | |
end | |
if route ~= nil then | |
ngx.var.upstream = route:gsub("^%s*(.-)%s*$", "%1") | |
routes:set(ngx.var.http_host, route) | |
else | |
ngx.exit(ngx.HTTP_NOT_FOUND) | |
end | |
'; | |
error_page 504 = @run; | |
proxy_buffering off; | |
proxy_set_header Host $host; | |
proxy_set_header X-Real-IP $remote_addr; | |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; | |
proxy_redirect off; | |
proxy_send_timeout 30; | |
proxy_read_timeout 30; | |
proxy_connect_timeout 2; | |
proxy_pass $scheme://$upstream; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment