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)
Related
I set up a flask/uwsgi and a nginx container.
First of all, I could not access the site having nginx listen on port 80 and defining the docker port 80:80. No idea why this would not work.
So I made nginx listen on port 8090 and opening port 80:8090 in docker:
nginx:
container_name: fa_nginx
build:
context: ./nginx
dockerfile: Dockerfile
restart: unless-stopped
ports:
- 80:8090
networks:
- fa_nginx_net
I am not exposing any ports in the dockerfile, there I copy just the conf file.
## nginx conf
server {
listen 8090;
location / {
include /etc/nginx/uwsgi_params;
uwsgi_pass web:8087;
}
Like that, I can access the site at http://localhost and browser around e.g. to http://localhost/faq.
However, when I submit a form (login), the nginx changes to another port and the redirected url looks like http://localhost:8090/auth/login.
the redirect in flask's login view after successful form validation is simply return redirect(url_for('main.profile')).
Here is the flask/uwsgi setup (shortened version without all then env etc):
web:
container_name: fa_web
build:
context: ./web
dockerfile: Dockerfile
expose:
- "8087"
networks:
- fa_nginx_net
[uwsgi]
plugin = python3
## python file where flask object app is defined.
wsgi-file = run.py
## The flask instance defined in run.py
callable = fapp
enable-threads = false
master = true
processes = 2
threads = 2
## socket on which uwsgi server should listen
protocol=http
socket = :8087
buffer-size=32768
## Gives permission to access the server.
chmod-socker = 660
vacuum = true
## various
die-on-term = true
## run.py
from app import create_app, db
import os
## init flask app
fapp = create_app()
if __name__ == "__main__":
if os.environ.get('FLASK_ENV') == 'development':
fapp.run(use_reloader=True, debug=True, host='0.0.0.0', port=8086)
else:
fapp.run(host='0.0.0.0', port=8087)
I have no idea why this is happening and how to solve this.
Ok, it is working now...
Basically I removed plugin=python3 and protocol=http from uwsgi.ini.
My setup looks now like this
## nginx default.conf
server {
listen 8090;
#server_name fa_web;
## To map the server block to an ip:
#server_name 1.2.3.4;
## To map the server block to a domain:
#server_name example.com www.example.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
include /etc/nginx/uwsgi_params;
uwsgi_pass web:8087;
}
}
## uwsgi.ini
[uwsgi]
## python file where flask object app is defined.
wsgi-file = run.py
## The flask instance defined in myapp.py
callable = fapp
enable-threads = false
master = true
processes = 2
threads = 2
## socket on which uwsgi server should listen
socket = :8087
buffer-size=32768
#post-buffering=8192 ## workaround for consuming POST requests
## Gives permission to access the server.
chmod-socker = 660
vacuum = true
## various
die-on-term = true
The added headers in nginx conf didn't make a difference, just added them going forward configuring everything correctly.
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
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 use Tornado and write some tests. And its everything fine.
Then I have used nginx for proxy:
server {
listen 80;
server_name mine.local;
location / {
proxy_pass http://localhost:8000;
}
}
It work nice. But.
In tests I use AsyncHTTPTestCase and get_app method, which returns Application.
The problem is: tests "looks" on default 127.0.0.1:8000 - Tornado starts on the port 8000, and all self.app.reverse_url('name') returns 127.0.0.1:8000/path.
But I need, that all requests from tests go to nginx (proxy):
mine.local/path
In hosts I have:
mine.local 127.0.0.1
In nginx I use some lua-scripts, that do all dirty-work. So I need, that tests make requests on mine.local, not on default 127.0.0.1:8000.
How to do this?
Thanks!
def bind_unused_port():
"""Binds a server socket to an available port on localhost.
Returns a tuple (socket, port).
"""
[sock] = netutil.bind_sockets(8000, 'localhost', family=socket.AF_INET)
port = sock.getsockname()[1]
return sock, port
class MineTestCase(AsyncHTTPTestCase):
def setUp(self):
super(AsyncHTTPTestCase, self).setUp()
sock, port = bind_unused_port()
self.__port = port
self.http_client = self.get_http_client()
self._app = self.get_app()
self.http_server = self.get_http_server()
self.http_server.add_sockets([sock])
def get_url(self, path):
url = '%s://%s:%s%s' % (self.get_protocol(), 'mine.local',
80, path)
return url