Should I change the localhost to be my public IP DNS address inside Nginx server config file? - amazon-ec2

My front-end in running on port 3000 and my back-end on port 8000.
I've deployed my app using EC2 instance and I've installed Nginx and PM2.
When I try to open the app on the browser using my public DNS address the app appears for a short period of time then it breaks. It shows me the error
net::ERR_CONNECTION_REFUSED
GET http://localhost:8000/api/info/countByType net::ERR_CONNECTION_REFUSED
Here is where my front-end is making the request
export const countByCity = createAsyncThunk("info/countByCity", async() => {
try{
const res = await axios.get("http://localhost:8000/api/info/countByCity");
return res.data;
}catch(error){
console.log(error.response)
}
});
and here is my /etc/nginx/sites-available/default file configuration
server {
listen 80;
listen [::]:80;
root /usr/share/nginx/booking.com;
index index.html index.htm index.nginx-debian.html;
server_name _;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri /index.html;
}
location /api {
proxy_pass http://ec2-54-167-89-197.compute-1.amazonaws.com:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
I have changed the proxy_pass to be my Public IP address. The previous configuration was http://localhost:8000.
My question is : My front end is trying to reach the localhost:8000 endpoint. Should I change it to be my Public DNS address instead? Example : http://ec2-54-167-89-197.compute-1.amazonaws.com/api/info/countByCity ?

This code in your front end is running in the user's web browser, not on the EC2 server:
const res = await axios.get("http://localhost:8000/api/info/countByCity");
When that code tries to access localhost it is trying to access a server running on your local laptop/PC, not a server in AWS. You need to change that localhost address to be the public IP of your EC2 server.
This proxy configuration on your Nginx server:
proxy_pass http://ec2-54-167-89-197.compute-1.amazonaws.com:8000;
Is going all the way out to the Internet and back, just to access a service that is running on a different port of the same server. You need to change that to be localhost for both security and efficiency.

Related

How to run bash script from Nginx

1) I have static site and wand to set "autopull" from bitbucket.
2) I have webhook from bitbucket.
3) I have bash script which do "git pull"
How can I run this script when nginx catch request?
server {
listen 80;
server_name example.ru;
root /path/to/root;
index index.html;
access_log /path/to/logs/nginx-access.log;
error_log /path/to/logs/nginx-error.log;
location /autopull {
something to run autopull.sh;
}
location / {
auth_basic "Hello, login please";
auth_basic_user_file /path/to/htpasswd;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
}
I tried lua_block and fastcgi service, but both are failed.
lua does not run os.execute("/path/to/script") and does not write the log.
fastcgi is more successful, but it has not permissions, because my www-data user doesn't have ssh-key in my bitbuchet repo.
Problem solved.
I didnt want to use any script/process on another port because I have several sites and I need port for each.
My final configuration is:
server {
listen 80;
server_name example.ru;
root /path/to/project;
index index.html;
access_log /path/to/logs/nginx-access.log;
error_log /path/to/logs/nginx-error.log;
location /autopull {
content_by_lua_block {
io.popen("bash /path/to/autopull.sh")
}
}
location / {
auth_basic "Hello, login please";
auth_basic_user_file /path/to/htpasswd;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
}
Problem was in permission of www-data user and its ssh-kay in repo.
Based on this, create py script
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from subprocess import call
PORT_NUMBER = 8080
autopull = '/path/to/autopull.sh'
command = [autopull]
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("runing {}".format(autopull))
call(command)
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
Run it and in nginx config add
location /autopull { proxy_pass http://localhost:8080; }

Nginx on OSX: "server" directive is not allowed here

I'm trying to serve a Node application through Nginx on my Mac, and I've run into a problem.
On Ubuntu, I always change the config file to this
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
but when I do the same on my Mac, I get this error when I'm running the server:
nginx: [emerg] "server" directive is not allowed here in
/usr/local/etc/nginx/nginx.conf:1
Any suggestions on why this is happening would be appreciated.
According to nginx's page http is the outer block. So it should work be adding a http block before the server block.
By doing that i get host not found in "$PORT" of the "listen" directive
http {
server {
listen $PORT;
server_name test-rpc.test.com;
location / {
proxy_ssl_server_name on;
proxy_pass http://test-rpc;
}
}
upstream test-rpc {
server localhost:2000 max_fails=3 fail_timeout=10s;
server localhost:2001 max_fails=3 fail_timeout=10s;
}
}

Flask sub.domain.com overrides session on domain.com

I have two seperate server one for domain.com and another for sub.domain.com, and I store sessions using flask-session and following configuration:
SERVER_NAME = 'domain.com'
SESSION_COOKIE_DOMAIN = ".domain.com"
# Flask-Session
SESSION_TYPE = 'redis'
SESSION_REDIS = Redis(host='192.168.10.10', port=6379, db=0)
further more I am using reverse proxy using nginx and:
proxy_set_header Host $host;
When I login on domain.com everything is ok but when I refresh sub.domain.com, user logs out on domain.com(sub.domain.com creates another session and overrides the one which is created by domain.com). Authentication is done by flask-login and it's on domain.com (sub.domain.com only should get them).
I don't know what's going wrong and I appreciate any help.
Update:
I tried to run flask without uwsgi and it works as it should, but when I uwsgi and nginx the problem persists. I think something is wrong with my uwsgi or nginx config.
# uwsgi.ini
[uwsgi]
master = true
enable-threads = true
process = 3
plugin = python
socket = /tmp/name.sock
base = /var/www/app
chdir = %(base)
wsgi-file = %(base)/manage.py
callable = app
# nginx.conf
server {
listen 8001;
location / {
include uwsgi_params;
uwsgi_pass unix:///tmp/name.sock;
}
}
By mistake I thought it has nothing to do with my reverse proxy or uwsgi. Actually it was problem with reverse proxy and I could solve my problem by adding following rules to nginx:
proxy_cookie_domain media.$host $host;
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_set_header Host $http_host;
proxy_redirect false;

block direct access on port 8080

I have an app running on a service, behind a nginx server, using unicorn.
If I access http://server.com I get the app, up and running...But I still can access app on port 8080, like http://server.com:8080 but this time, without assets (which are beign served by nginx)
How do I block direct access to port 8080 on my prod. server?
The server is an Ubuntu 12.04
nginx.conf
upstream unicorn {
server 127.0.0.1:8080;
}
server {
listen 80 default deferred;
# server_name example.com;
root /home/deploy/current/public;
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
try_files $uri/index.html $uri #unicorn;
location #unicorn {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://unicorn;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}
Make unicorn and nginx use a domain socket. For nginx:
upstream unicorn {
server unix:/path/to/socket fail_timeout=0;
}
Then pass '-l /path/to/socket' to unicorn, or alter your unicorn config file:
listen '/path/to/socket'

nginx - rewrite domain.com:port to sub.domain.com

How can i rewrite a domain with a port to a subdomain?
e.q.: domain.com:3000 to sub.domain.com ?
thanks for your help! :)
greetz
If you actually want to redirect (301 or 302) your web traffic
You create a server {} section listening on port 3000 and you just redirect it to another server {} section that is listening on port 80. In each server {} section set the listen property appropriately.
I guess you are trying to handle the redirection within à single server section and according to this page the listen directive applies to a server context
If you want to use nginx as a proxy
Then what you are looking for is the proxy_pass directive. Here is a sample configuration extracted from an config I have to use nginx as a proxy for my rails app (thin). Basically my app runs locally (but it would also work on a remote host) on port 3200 and the relevant nginx config part looks as follow:
upstream my-app-cluster
{
server localhost:3200;
}
server
{
listen 80;
server_name mydomain.com;
root /root/to/public/folder;
access_log /my/app/log/folder/myapp.log;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
if (-f $request_filename/index.html) {
rewrite (.*) $1/index.html break;
}
if (-f $request_filename.html) {
rewrite (.*) $1.html break;
}
if (!-f $request_filename) {
proxy_pass http://my-app-cluster;
break;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
You could use Passenger in nginx to delivery the Ruby app - that's the method we are currently using.
http://www.modrails.com/

Resources