ngnix code

Create Ngnix server with docker

docker pull nginx

docker run -p 80:80 -d nginx

le fichier de conf de l'image docker ngnix par défaut:
situé à /etc/ngnix/ngnix.conf

docker commit  "Nom du stapshot"
=> renvoie id
docker run -p 80:80 -d id

Fichier de conf nginx.conf

user  ngnix;
#Defines which Linux system user will own and run the Nginx server top process

worker_processes  4;
#max process number. Generally set to be equal to the number of CPUs cores.

error_log  /var/logs/ngnix/error.log; #error_log  logs/error.log  notice;
#Specifies the file where server logs is located. 
# less /var/logs/ngnix/error.log to see error logs
access_log /var/logs/ngnix/access.log;
# less /var/logs/ngnix/access.log to see error logs
#tail /var/logs/ngnix/access.log

pid  /var/run/nginx.pid;
#nginx will write its master process ID (PID).

Ngnix as Reverse Proxy

Reverse proxy can:
* hide existence of original backend servers
* protect backend servers from web based attackes, DOS ...
* provide caching fonctionalities
* optimize the content by using compression
* act as SSL Terminaison proxy
* Route requests

Reverse proxy configuration: proxy_pass directive
proxy_pass directive forwards the request to the proxied server specified along with the directive:

X-Real-IP & Proxy Host Header

Lorsque ngnix est utilisé comme reverse proxy, les serveurs derrière ngnix doivent recevoir l'IP du client, pour que ces serveurs renseignent en retour ngnix sur l'IP à laquelle forwarder la réponse. (par défaut, les backend serveurs reçoivent l'ip d'ngnix)

En effet lors que 3 clients distincts requêtent ngnix, ngnix doit alors donner la réponse appropriée à chaque client.
pour que les backends serveurs revoivent la vraie ip du client:

Ngnix as Load Balancer


Répartir les requêtes sur plusieurs serveurs backend:

upstream backend {
  server 172.17.0.2;
  server 172.17.0.3;
}

server {
 listen 80;
 server_name example.com
  location {
   proxy_pass http:// backend;
   proxy_set_header ...;
  }
}

la première requête sera transmise à 172.17.0.2
la seconde à 172.17.0.3

Health care:
the load balancer has to know when a backend server is up or down
there are 2 types of Heath check: Active Heath checks (only in Ngnix X paid version) and Passive heath check

Ngnix caching

Cache control Headers:

  • Do not store any kind of cache at all
  • Store the cahche but verify with webserver whether file is modified
  • Store the cache for 24h
  • ...

various cache control headers:

  • Cache-Control: no-store
  • Cache-Control: no-cache
  • Cache-Control: no-store, no-cache must-revalidate
  • Cache-Control: public
  • Cache-Control: private
  • ...

Cache-Control: no-cache

Ngnix staic Assets

server {
        server_name  example.com;

           location / {
            proxy_pass http:// 192.168.1.100;
          }

           location ~* \.(css|js|jp?g|JPG|png)  {
               root /var/www/assets          
              try_files $uri $uri/;
          }

 }

Whitelist IP in NGINX for URL

# ...
 server {
     listen 80;
     server_name www.example.com;


     location /accounts/login {
        allow 45.43.23.21;
        deny all;
     }

     location /api {
         limit_except GET {
             auth_basic "NGINX Plus API";
             auth_basic_user_file /path/to/passwd/file;
         }

         api   write=on;

         allow 127.0.0.1;
         deny  all;
     }
 }

sudo nginx -t
sudo service nginx reload #debian/ubuntu
systemctl restart nginx #redhat/centos

Ngnix Spf daddy dockerfile :)

# Use the Python3.7.2 image
FROM nginx

# Set the working directory to /app
WORKDIR /app



RUN apt-get update
RUN apt-get upgrade
RUN apt-get -y install curl
RUN apt-get -y install libncurses5-dev libncursesw5-dev libncurses5


# Copy the current directory contents into the container at /app 
ADD ./spf /app/spf
ADD ./help.txt /app/help.txt

RUN mv /app/spf /bin/spf
RUN mv /app/help.txt /bin/help.txt
RUN chmod +x /bin/spf

RUN mkdir /app/html
ADD ./html/index.html /app/html/index.html

RUN rm /etc/nginx/conf.d/default.conf

Docker compose to run Php & Python in same domain

version: '3'

services:
  nginx:
    image: nginx
    restart: unless-stopped
    container_name: web-nginx
    volumes:
      - ./data/nginx:/etc/nginx/conf.d
      - ./data/html:/usr/share/nginx/html:ro
    ports:
      - "80:80"
      - "443:443"
  web-php:
    image: php:fpm-alpine
    container_name: web-php
    volumes:
      - ./data/docker-web/www:/script:ro
  flask:
    build: ./data/flask
    container_name: flask
    restart: always
    environment:
      - APP_NAME=MyFlaskApp
      - FLASK_APP=run.py
      - FLASK_ENV=development
      - FLASK_DEBUG=1

/data/nginx/app.conf

/data/flask/run.py

 
from app import app

if __name__ == "__main__":
    app.run()

/data/flask/app.ini

 
[uwsgi]
wsgi-file = run.py
callable = app
socket = :8080
processes = 4
threads = 2
master = true
chmod-socket = 660
vacuum = true
die-on-term = true

/data/flask/Dockerfile

 
# Use the Python3.7.2 image
FROM python:3.7.2-stretch

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app 
ADD . /app

# Install the dependencies
#RUN pip install -r requirements.txt
RUN pip install flask uwsgi

#VOLUME /app

# run the command to start uWSGI
CMD ["uwsgi", "app.ini"]

/data/flask/app/__init__.py

 
from flask import Flask

app = Flask(__name__)

from app import views

/data/flask/app/views.py

 
from app import app
import os

@app.route("/py")
def index():

    # Use os.getenv("key") to get environment variables
    app_name = os.getenv("APP_NAME")

    if app_name:
        return f"Hello from python {app_name} running in a Docker container behind Nginx!"

    return "Hello from Flask"

/data/docker-web/www/index.php

 
<?php
 
phpinfo
();
?>