Using NGINX in Docker

Using NGINX in Docker

Tags
Published
Link

Dockerfile to deploy a React App

# Use a lightweight Node.js image FROM node:20.15.1-slim AS build # Set the working directory WORKDIR /app # Install Yarn using corepack RUN npm install yarn # Copy package.json and yarn.lock to install dependencies COPY package*.json yarn.lock ./ # Install dependencies RUN yarn install # Copy the rest of the application files COPY . . # Build the application RUN yarn build # Use a lightweight server for the final production stage FROM nginx:alpine AS production # Copy the build output to the nginx default public folder COPY --from=build /app/build /usr/share/nginx/html # Expose the port nginx listens on EXPOSE 80 # Start nginx CMD ["nginx", "-g", "daemon off;"]

Why use NGINX

Nginx is a high-performance, lightweight, and reliable web server that is widely used for serving static files, reverse proxying, load balancing, and more. It is highly optimized for production environments, making it a common choice for serving React, Angular, or Vue applications.
Why Use Nginx to Serve Static Files?
  1. Fast and Efficient: Nginx efficiently handles static content (HTML, CSS, JS, and images) with minimal overhead. It performs better than Node.js servers (like serve or Express) in speed and resource usage.
  1. Low Resource Consumption: Nginx's event-driven, non-blocking architecture handles thousands of requests using minimal memory and CPU. This makes it perfect for performance-critical production deployments.
  1. Security: Nginx includes rate limiting, HTTP headers management (CSP, HSTS), and DDoS protection. It has a smaller attack surface than Node.js servers.
  1. Reliability: Nginx offers robust health checks and failover mechanisms. It handles heavy loads better than JavaScript-based servers.
  1. Built-In Static File Serving: Nginx serves static files directly without requiring Node.js, simplifying deployment.
  1. Reverse Proxy Capabilities: As a reverse proxy, Nginx smoothly integrates with backend services, APIs, and containerized apps.
  1. Compression Support: Built-in gzip and Brotli compression reduces file sizes and speeds up loading.
  1. Caching: Nginx caches static content to avoid repeated disk reads.
  1. Scalability: Nginx efficiently manages large numbers of concurrent connections, making it ideal for high-traffic websites.