Skip to content

Nginx#

Test nginx configuration#

nginx -t

Reload nginx (config changes)#

systemctl reload nginx

Restart nginx#

systemctl restart nginx

Check nginx status#

systemctl status nginx

View nginx error logs#

tail -f /var/log/nginx/error.log

View site error logs#

tail -f /var/log/nginx/hospital-backend-error.log

View site access logs#

tail -f /var/log/nginx/hospital-backend-access.log

List enabled sites#

ls -la /etc/nginx/sites-enabled/

Enable site#

ln -s /etc/nginx/sites-available/sitename /etc/nginx/sites-enabled/

Disable site#

rm /etc/nginx/sites-enabled/sitename

Check nginx version#

nginx -v

Make it persistent (systemd service)#

File:

sudo nano /etc/systemd/system/projectA.service
[Unit]
Description=Project A Backend
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/var/www/projectA
ExecStart=/var/www/projectA/venv/bin/gunicorn config.wsgi:application --bind 127.0.0.1:8000
Restart=always

[Install]
WantedBy=multi-user.target

Commands:

sudo systemctl daemon-reload
sudo systemctl enable projectA
sudo systemctl start projectA

Nginx setup (multiple projects)#

Project A#

sudo nano /etc/nginx/sites-available/projectA
server {
    listen 80;
    server_name api.a.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}

Enable:

sudo ln -s /etc/nginx/sites-available/projectA /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Project B → SAME PROCESS, DIFFERENT PORT + DOMAIN#


SAME THING WITH DOCKER


Docker backend (no proxy inside container)#

docker-compose.yml#

version: "3.9"
services:
  api:
    build: .
    container_name: projectA_api
    ports:
      - "127.0.0.1:8000:8000"
    command: gunicorn config.wsgi:application --bind 0.0.0.0:8000

Run:

docker compose up -d --build

8️⃣ Nginx stays SAME#

proxy_pass http://127.0.0.1:8000;

Nginx does not care if backend is Docker or not.


PDOCKER + INTERNAL NETWORK#


9️⃣ Docker-only networking (no ports exposed)#

services:
  api:
    build: .
    expose:
      - "8000"
    networks:
      - backend

# this can be another container okie 
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf
    networks:
      - backend

networks:
  backend:

nginx.conf#

server {
    listen 80;
    server_name api.a.com;

    location / {
        proxy_pass http://api:8000;
    }
}

api works ONLY because nginx is inside same docker network