# Nginx
Nginx (pronounced "engine-x") is a high-performance web server and reverse proxy server. It is widely used for serving static content, load balancing, handling high concurrency, and acting as a gateway to backend applications.
#### Why Use It:
* High performance and scalability – Efficiently handles thousands of simultaneous connections.
* Load balancing – Distributes traffic across multiple servers.
* Reverse proxying – Secures and accelerates backend services.
* Static file serving – Excellent for serving HTML, CSS, JS, and media content.
* Resource efficiency – Low memory usage compared to alternatives like Apache.
---
## Confusing Concepts explained
### 🔐 TLS v1.2/1.3, Self-Signed vs RSA?
#### ✅ TLS v1.2 / v1.3
TLS (Transport Layer Security) encrypts traffic (e.g., HTTPS).
v1.3 is newer, faster, and more secure than v1.2.
#### ✅ Self-signed Certificate:
Created by you, not verified by a public authority.
Used in internal/dev environments (e.g., your Docker Nginx server).
#### ✅ RSA:
RSA is the algorithm used to generate TLS certificates (public/private key pairs).
You can have RSA self-signed certs or RSA certs signed by a CA.
---
---
# Setup + Test
After implement for dockerfile & config, test:
## step 1 | build image
```bash
docker build
docker build --help
```
```bash
docker build -t [image_name] [(argument)where to run the docker build]
```
---
## step 2 | After image build => several check command
### 1. Check image log list
```bash
docker images
```
#### Example
```bash!
➜ nginx git:(master) ✗ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx1 latest d1fcc5643d79 30 minutes ago 205MB
```
### 2. Check history of certain image
```bash!
docker history [created_image_name]
```
#### Example
```bash!
➜ inception git:(master) ✗ docker history nginx1
IMAGE CREATED CREATED BY SIZE COMMENT
d1fcc5643d79 32 minutes ago CMD ["nginx" "-g" "daemon off;"] 0B buildkit.dockerfile.v0
<missing> 32 minutes ago EXPOSE map[443/tcp:{}] 0B buildkit.dockerfile.v0
<missing> 32 minutes ago RUN /bin/sh -c mkdir -p /run/nginx # buildkit 0B buildkit.dockerfile.v0
<missing> 32 minutes ago RUN /bin/sh -c openssl req -x509 … 3.01kB buildkit.dockerfile.v0
<missing> 32 minutes ago RUN /bin/sh -c mkdir -p /etc/nginx/ssl # bui… 0B buildkit.dockerfile.v0
<missing> 32 minutes ago RUN /bin/sh -c apt-get update && apt-get… 80.7MB buildkit.dockerfile.v0
<missing> 2 weeks ago # debian.sh --arch 'amd64' out/ 'bullseye' '… 124MB debuerreotype 0.15
```
### 3. Check Build Cache
```bash
docker system df
```
#### => What is Build Cache?
+ Build cache is Docker's way of speeding up builds by reusing previously built layers.
+ When you run ```docker build```, Docker creates layers for each instruction in your Dockerfile. Instead of rebuilding everything from scratch each time, Docker saves these layers and reuses them if nothing has changed.
#### Example:
If you rebuild and only change **nginx.conf**, Docker will:
✅ Reuse Layers 1-3 (from cache)
🔄 Rebuild Layer 4 and any layers after it
### 4. check detailed image info
```bash
docker inspect [created_image_name]
```
**=> Level: Image/container**
**=> View full metadata of an image or container:**
+ Shows disk usage details of the build cache used by Docker BuildKit.
+ Requires that you're using docker buildx (advanced builder backend).
### 4. Check Build Cache Details
```bash
docker buildx du
```
**=> Level: Build system**
**=> Analyze disk usage by build cache**
---
## Command Table
| **Category** | **Command** | **Description** |
| ------------------------ | ------------------------- | --------------------------------------------------------------- |
| 🔍 **Image Information** | `docker images` | List all locally built images |
| | `docker history <image>` | Show image build layers and Dockerfile commands |
| | `docker inspect <image>` | Display detailed metadata for the image |
| 🧱 **Build Cache** | `docker system df` | Show overall disk usage including images, containers, and cache |
| | `docker buildx du` | Display detailed build cache usage (requires BuildKit) |
| | `docker buildx prune` | Clean up unused build cache |
| 🧾 **Container History** | `docker ps -a` | List all containers (running and stopped) |
| | `docker logs <container>` | View logs from a specific container |
---
## After cheking image created succesfully, ...
## step 3 | init container
```bash
docker run
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
```
```bash
docker run --rm --name nginx_test -p 8080:443 nginx1
```
### What it does:
1. Creates a new container from the nginx1 image
2. Names it nginx_test
3. Maps your computer's port 8080 to the container's port 443
4. Starts nginx inside the container
5. When you stop it, automatically removes the container
### Common Flags Explained
| **Flag** | **Purpose** | **Example** |
| ----------- | ------------------------------------------- | ------------------------------- |
| `--rm` | Automatically remove container on exit | `--rm` |
| `--name` | Assign a custom name to the container | `--name my_container` |
| `-p` | Map host port to container port | `-p 8080:443` |
| `-d` | Run container in detached mode (background) | `-d` |
| `-it` | Allocate interactive terminal | `-it` |
| `-e` | Set environment variables | `-e VAR=value` |
| `-v` | Mount a host volume into the container | `-v /host/path:/container/path` |
| `--network` | Connect to a custom Docker network | `--network my_network` |
---
---
## After init container, ...
## step 4 | check if container running succesfully
### Go to another terminal, run:
```bash
docker ps
docker ps -a
```
#### Example:
```bash
➜ srcs git:(master) ✗ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cc0093abd8f8 nginx1 "nginx -g 'daemon of…" About a minute ago Up About a minute 0.0.0.0:8080->443/tcp, [::]:8080->443/tcp nginx_test
```
**=> Status Breakdown:**
+ **Up About a minute ✅** = Container is RUNNING for about 1 minute
+ **0.0.0.0:8080->443/tcp ✅** = Port mapping is active (host:8080 → container:443)
**❌ If it was stopped, you would see:**
```bash
STATUS
Exited (0) 2 minutes ago
```
---
---
## After Container running succesfully, ...
## step 5 | test container
### [A] without server setup
```bash
docker logs [created_container_name]
```
**=> No error logs means nginx is running smoothly.**
### [B] with server setup
~~........TBD~~
### [C] try go inside container to run tests:
#### Method 1: Execute a Shell Inside the Container
```bash
docker exec -it [created_container_name] sh
```
(OR)
```bash
docker exec -it [created_container_name] bash
```
+ ```docker exec```: Execute a command in a running container
+ ```-it```: Interactive terminal (allows you to type commands)
+ ```nginx_test```: The container name
sh: The shell command to run
#### Method 2: do general inspection/debug
**1. Check Nginx Configuration**
```bash
# View nginx configuration
cat /etc/nginx/nginx.conf
# Test nginx configuration syntax
nginx -t
# View all nginx config files
ls -la /etc/nginx/
# Check if nginx is running
ps aux | grep nginx
```
**2. Inspect SSL Certificates**
```bash
# Check if SSL certificates exist
ls -la /etc/nginx/ssl/
# View certificate details
openssl x509 -in /etc/nginx/ssl/inception.crt -text -noout
# Check certificate expiry
openssl x509 -in /etc/nginx/ssl/inceptiocker logs nginx_container1on.crt -dates -noout
```
**3. Check File System Structure**
```bash
# Check web root directory
ls -la /var/www/html/
# Check nginx logs directory
ls -la /var/log/nginx/
# Check running processes
ps aux
# Check listening ports
netstat -tulpn # or ss -tulpn
```
**4. Debug Network Issues**
```bash
# Test connectivity to other services
ping wordpress # (won't work yet since wordpress isn't running)
# Check network interfaces
ip addr show
# Check DNS resolution
nslookup wordpress
```
**5. View Logs**
```bash
# Check nginx access logs
tail -f /var/log/nginx/access.log
# Check nginx error logs
tail -f /var/log/nginx/error.log
# Check system logs
dmesg
```
**6. Test Nginx Functionality**
```bash
# Create a simple test file
echo "Hello from Nginx!" > /var/www/html/index.html
# Test nginx internally
curl -k https://localhost:443
# Check nginx status
nginx -s reload # Reload configuration
```
**7. Package Management**
```bash
# Check installed packages
dpkg -l | grep nginx
# Install additional tools (if needed)
apt-get update
apt-get install curl vim nano
```
**8. Environment Variables**
```bash
# Check environment variables
env
# Check specific variables
echo $PATH
```
#### Method 3: test outside nginx
```bash
docker exec nginx_test nginx -t
```
=> Test nginx configuration inside [container] using the correct command
```bash
docker exec nginx_test ls -la /etc/nginx/ssl/
```
=> Check if SSL certificates exist in the container
---
---
## After container correctly set-up, ...
## step 6 | test container functionality
### 1. Process Inspection | Check Nginx Status and Logs
```bash
docker exec nginx_container1 ps aux | grep nginx
```
=> Confirm Nginx is running.
=> See how many worker processes exist.
=> Check for unexpected process crashes or restarts.
### 2. Network Port Check
```bash
docker exec [container_name] netstat -tulpn | grep :[443(port nb)]
```
=> Shows network ports being listened to inside the container.
=> Filters for port 443 (HTTPS).
```bash
docker exec nginx_container1 cat /etc/nginx/nginx.conf | grep -A 20 "server {"
```
=> Check what (port) ```nginx.conf``` listens on
```bash
docker port [containter_name]
```
=> Shows the port mappings between the container's internal ports and the host system's ports
#### Example:
```bash
443/tcp -> 0.0.0.0:8080
443/tcp -> [::]:8080
```
**=> Key insights:**
+ Container's internal port 443 is mapped to host's port 8080
+ This mapping works for both IPv4 (0.0.0.0:8080) and IPv6 ([::]:8080)
+ When you access https://localhost:8080 from your host machine, Docker forwards that traffic to port 443 inside the container
**The Complete Picture**
```bash
Host Machine Container
┌─────────────┐ ┌─────────────┐
│ │ │ │
│ Port 8080 │ ──── │ Port 443 │
│ (HTTPS) │ │ (nginx) │
│ │ │ │
└─────────────┘ └─────────────┘
```
**=> Flow:**
- You request https://localhost:8080 from your browser/curl
- Docker forwards this to port 443 inside the container
- Nginx (listening on 443) receives the request
- Nginx serves content from /var/www/html using SSL certificates
- Response travels back through the same path
- This is why curl -k https://localhost:8080 works - the port mapping bridges the gap between your host system and the containerized nginx service.
### 3. Check if html file is created
```bash
docker exec nginx_container1 ls -la /var/www/html/
```
### 4. Check nginx error logs to see what's happening
```bash
docker exec nginx_container1 tail -f /var/log/nginx/error.log
```
### 4. Test if nginx works internally without SSL
### [A]
```bash
docker exec nginx_container1 curl -k https://localhost:443
```
OR (as in container not installed ```curl```)
### [B]
#### 1. Test from Your Host Machine:
```bash
curl -k https://localhost:8080
```
##### Example:
```bash
➜ nginx git:(master) ✗ curl -k https://localhost:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
```
=>
✅ SSL is working: The ```-k``` flag bypassed certificate warnings, and you got a response
✅ Custom nginx.conf is loaded: You're getting the default nginx page, which means your configuration is working
✅ Port mapping works: localhost:8080 → container:443 is functioning
✅ Container is healthy: Nginx is serving content properly
#### 2. Check if Your Custom HTML File Exists
```bash
docker exec nginx_container1 ls -la /var/www/html/
```
#### 3. Create a Custom Test Page
(complete gothru)
```bash!
#remove the newlines
docker exec nginx_container1 bash -c 'echo
"<h1>YOOO!! My Custom Nginx Page!</h1>
<p>This content was changed from outside the container!</p>
<p>SSL is working perfectly!</p>"
> /var/www/html/index.html'
```
#### 4. Test the Custom Page (open browser to check)
```bash
curl -k https://localhost:8080
```
---
---
# Cleanup Commands
```bash
# Stop specific container
docker stop <container_name>
# Remove specific container
docker rm <container_name>
# Remove specific image
docker rmi <image_name>
# Nuclear option - clean everything unused
docker system prune -af --volumes
```