I have a working openresty with lua-resty-openidc as ingress controller.
Now, the nginx.conf is hardcoded in my image, with something like this :
server {
server_name _;
listen 80;
location /OAuth2Client {
access_by_lua_block {
local opts = {
discovery = "/.well-known/openid-configuration",
redirect_uri = "/authorization-code/callback",
client_id = "clientID",
client_secret = "clientSecret",
scope = "openid profile somethingElse",
}
...
}
proxy_pass http://clusterIp/OAuth2Client;
}
}
As Nginx doesn't accept environment variables, is there a simple way to make my nginx.conf configurable, for ex
server {
server_name ${myServerName};
listen ${myServerPort};
location /${specificProjectRoot} {
access_by_lua_block {
local opts = {
discovery = "${oidc-provider-dev-url}/.well-known/openid-configuration",
redirect_uri = "${specificProjectRoot}/authorization-code/callback",
client_id = "${myClientId}",
client_secret = "${myClientSecret}",
scope = "${myScopes}",
}
...
}
proxy_pass http://${myClusterIP}/${specificProjectRoot};
}
}
so that whatever team in whatever namespace could reuse my image and just provide a kubernetes secret containing their specific config for their project ?
You would need to render the nginx.conf from a templated version at runtime (as Juliano's comment mentions). To do this, your Dockerfile could look something like this:
FROM nginx
COPY nginx.conf.template /etc/nginx/
CMD ["/bin/bash", "-c", "envsubst < /etc/nginx/nginx.conf.template > /etc/nginx/nginx.conf && exec nginx -g 'daemon off;'"]
Notice that it copies nginx.conf.template into your image, this would be your templated config with variables in the form ${MY_SERVER_NAME} where MY_SERVER_NAME is injected into your pod as an environment variable via your Kubernetes manifest, from your configmap or secret or however you prefer.
While envsubst is a good workaround to connect Kubernetes objects with container files, Kubernetes native ConfigMaps are designed precisely for this purpose: passing non-sensitive key-value data to the container, including entire files like your nginx.conf.
Here's a working example (in the question AND answer) of a ConfigMap and Deployment pair specifically for NGINX:
Custom nginx.conf from ConfigMap in Kubernetes
Related
I have two servers:
NGINX (it exchanges file id to file path)
Golang (it accepts file id and return it's path)
Ex: When browser client makes request to https://example.com/file?id=123, NGINX should proxy this request to Golang server https://go.example.com/getpath?file_id=123, which will return the response to NGINX:
{
data: {
filePath: "/static/..."
},
status: "ok"
}
Then NGINX should get value from filePath and return file from the location.
So the question is how to read response (get filePath) in NGINX?
I assume you are software developer and your have full control over your application so there is no need to force square peg in a round hole here.
Different kinds of reverse proxies support ESI(Edge Side Includes) technology which allow developer to replace different parts of responce body with content of static files or with response bodies from upstream servers.
Nginx has such technology as well. It is called SSI (Server Side Includes).
location /file {
ssi on;
proxy_pass http://go.example.com;
}
Your upstream server can produce body with content <!--# include file="/path-to-static-files/some-static-file.ext" --> and nginx will replace this in-body directive with content of the file.
But you mentioned streaming...
It means that files will be of arbitrary sizes and building response with SSI would certainly eat precious RAM resources so we need a Plan #B.
There is "good enough" method to feed big files to the clients without showing static location of the file to the client.
You can use nginx's error handler to server static files based on information supplied by upstream server.
Upstream server for example can send back redirect 302 with Location header field containing real file path to the file.
This response does not reach the client and is feed into error handler.
Here is an example of config:
location /file {
error_page 302 = #service_static_file;
proxy_intercept_errors on;
proxy_set_header Host $host;
proxy_pass http://go.example.com;
}
location #service_static_file {
root /hidden-files;
try_files $upstream_http_location 404.html;
}
With this method you will be able to serve files without over-loading your system while having control over whom do you give the file.
For this to work your upstream server should respond with status 302 and with typical "Location:" field and nginx will use location content to find the file in the "new" root for static files.
The reason for this method to be of "good enough" type (instead of perfect) because it does not support partial requests (i.e. Range: bytes ...)
Looks like you are wanting to make an api call for data to run decision and logic against. That's not quite what proxying is about.
The core proxy ability of nginx is not designed for what you are looking to do.
Possible workaround: extending nginx...
Nginx + PHP
Your php code would do the leg work.
Serve as a client to connect to the Golang server and apply additional logic to the response.
<?php
$response = file_get_contents('https://go.example.com/getpath?file_id='.$_GET["id"]);
preg_match_all("/filePath: \"(.*?)\"/", $response, $filePath);
readfile($filePath[1][0]);
?>
location /getpath {
try_files /getpath.php;
}
This is just the pseudo-code example to get it rolling.
Some miscellaneous observations / comments:
The Golang response doesn't look like valid json, replace preg_match_all with json_decode if so.
readfile is not super efficient. Consider being creative with a 302 response.
Nginx + Lua
sites-enabled:
lua_package_path "/etc/nginx/conf.d/lib/?.lua;;";
server {
listen 80 default_server;
listen [::]:80 default_server;
location /getfile {
root /var/www/html;
resolver 8.8.8.8;
set $filepath "/index.html";
access_by_lua_file /etc/nginx/conf.d/getfile.lua;
try_files $filepath =404;
}
}
Test if lua is behaving as expected:
getfile.lua (v1)
ngx.var.filepath = "/static/...";
Simplify the Golang response body to just return a bland path then use it to set filepath:
getfile.lua (v2)
local http = require "resty.http"
local httpc = http.new()
local query_string = ngx.req.get_uri_args()
local res, err = httpc:request_uri('https://go.example.com/getpath?file_id=' .. query_string["id"], {
method = "GET",
keepalive_timeout = 60,
keepalive_pool = 10
})
if res and res.status == ngx.HTTP_OK then
body = string.gsub(res.body, '[\r\n%z]', '')
ngx.var.filepath = body;
ngx.log(ngx.ERR, "[" .. body .. "]");
else
ngx.log(ngx.ERR, "missing response");
ngx.exit(504);
end
resty.http
mkdir -p /etc/nginx/conf.d/lib/resty
wget "https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http_headers.lua" -P /etc/nginx/conf.d/lib/resty
wget "https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http.lua" -P /etc/nginx/conf.d/lib/resty
I'm trying to make an http request using lua-resty-http.
I created a simple get api in https://requestb.in
I can make a request using the address: https://requestb.in/snf2ltsn
However, when I try to do this in nginx I'm getting error no route to host
My nginx.conf file is:
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
lua_package_path "$prefix/lua/?.lua;;";
server {
listen 8080;
location / {
resolver 8.8.8.8;
default_type text/html;
lua_code_cache off; #enables livereload for development
content_by_lua_file ./lua/test.lua;
}
}
}
and my Lua code is
local http = require "resty.http"
local httpc = http.new()
--local res, err = httpc:request_uri("https://requestb.in/snf2ltsn", {ssl_verify = false,method = "GET" })
local res, err = httpc:request_uri("https://requestb.in/snf2ltsn", {
method = "GET",
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
}
})
How can I fix this Issue?
Or is there any suggestion to make http request in nginx?
any clue?
PS: There is a commented section in my Lua code. I also tried to make a request using that code but nothing happened.
Change the package_path like:
lua_package_path "$prefix/resty_modules/lualib/?.lua;;";
lua_package_cpath "$prefix/resty_modules/lualib/?.so;;";
By default nginx resolver returns IPv4 and IPv6 addresses for given domain.
resty.http module uses cosocket API.
Cosocket's connect method called with domain name selects one random IP address You are not lucky and it selected IPv6 address. You can check it by looking into nginx error.log
Very likely IPv6 doesn't work on your box.
To disable IPv6 for nginx resolver use directive below within your location:
resolver 8.8.8.8 ipv6=off;
I would like to proxy the subpaths of my website to another service:
http://some-web-site.com/friends/ - renders /friends/index.html
http://some-web-site.com/friends/ [not empty request path] - proxy to another service.
Currently I have the following Nginx configuration:
location /programming/ {
(...)
proxy_pass http://tomcat:8080/friends;
}
But unfortunately this proxies /programming/ to http://tomcat:8080/friends.
Use an exact match location block to extract specific URIs for special handling:
location = /programming/ {
...
}
location /programming/ {
...
proxy_pass http://tomcat:8080/friends;
}
See this document for details.
I am new to NGINX, uWSGI AND Pyramid, and I am trying to serve a Pyramid app through uWSGI using nginx as a reverse proxy. I am really stuck at the moment and am hoping someone can make some suggestions for how to solve this. If you can explain a little what might be going on, that would be helpful too, as my understanding is very limited!
Currently, I am getting an `Internal Server Error' from uWSGI when I visit the reverse proxy URL. In the uWSGI error log, I am getting the error:
--- no python application found, check your startup logs for errors ---
The application works fine when I serve through uWSGI alone, launching with pserve. I can launch it from my virtual envelope as follows:
bin/pserve my-app/uwsgi.ini
But when I start nginx, and visit the proxy address, I get the Internal Server Error.
The settings I have in uwsgi.ini are as follows:
[app:main]
use = egg:myapp
pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = false
pyramid.debug_routematch = false
pyramid.default_locale_name = en
pyramid_debugtoolbar
[server:main]
use = egg:waitress#main
host = 0.0.0.0
port = 6543
[loggers]
keys = root, musiccircle
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = ERROR
handlers = console
[logger_musiccircle]
level = ERROR
handlers =
qualname = musiccircle
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s
[uwsgi]
socket = unix://home/usr/env/myapp/myapp.sock
master = true
processes = 48
cpu-affinity = 12
harakiri = 60
post-buffering = 8192
buffer-size = 65535
daemonize = ./uwsgi.log
pidfile = ./pid_5000.pid
listen = 32767
reload-on-as = 512
reload-on-rss = 192
limit-as = 1024
no-orphans = true
reload-mercy = 8
log-slow = true
virtualenv = /home/usr/env
And in the corresponding myapp.conf file in nginx, I have the following:
upstream myapp {
server 127.0.0.1:6543;
}
server {
listen 8080;
server_name myapp.local www.myapp.local;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/usr/env/myapp;
}
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
charset utf-8;
location / {
include uwsgi_params;
uwsgi_pass unix://home/usr/env/myapp/myapp.sock;
}
}
If you need to see anything else, please let me know. As you can see, Nginx is configured to serve at port 8080 (which it does), and the Pyramid app is being served by uWSGI to port 6543 (which it does).
Thanks in advance.
It seems Pyramid projects are intended to be installed (setup.py) and then run with a .ini configuration file with pserve. Pserve then passes in these config file details as **settings to your Pyramid app at run time.
This is different than, say, Flask which is not installed and generally has no configuration file. Such a Flask application can be run by uWSGI as needed, with all run-time configuration being handled by uWSGI or environment variables.
Since Pyramid usually needs a config file at run time, and relies on pserve to provide them when using a config file (ie production.ini), I think you'll have to run uwsgi --ini-paste production.ini (or if running with Pypy, uwsgi --pypy-paste production.ini) (thanks to #Sorrel)
I have nginx 1.0.8 installed.
here is my problem:
I have 2 files : file1.js and file2.js. the requested path is something like this:
www.mysite.com/files_dir/%user%/file.js
If the requested header : "X-Header" exists and has the value "OK" then the responded content should be file1.js else file2.js.
The files are situated in "html/files_dir" and %user% is a set of directories that represents the usernames registered through my service.
How do I configure this in nginx? I'm not interested in php, asp or similar technologies only if it's possible with nginx.
Thanks
map lets you define a variable's value based on another variable. map should be declared at http level (i.e. outside of server):
map $http_x_header $file_suffix {
default "2";
OK "1";
};
Then the following location should do the trick using your new variable $file_suffix
location ~ ^(/files_dir/.+)\.js$ {
root html;
try_files $1$file_suffix.js =404;
}
You could do this with nginx very easily. This is example:
location /files_dir/ {
set $file = file2.js;
if ( $http_x_header = OK ) {
set $file = file1.js;
}
rewrite ^(/files_dir/.*)/file.js$ $1/$file last;
}
You could read about HTTP variables in NGINX here , and about nginx rewrite module here