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?
- 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.
- 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.
- Security: Nginx includes rate limiting, HTTP headers management (CSP, HSTS), and DDoS protection. It has a smaller attack surface than Node.js servers.
- Reliability: Nginx offers robust health checks and failover mechanisms. It handles heavy loads better than JavaScript-based servers.
- Built-In Static File Serving: Nginx serves static files directly without requiring Node.js, simplifying deployment.
- Reverse Proxy Capabilities: As a reverse proxy, Nginx smoothly integrates with backend services, APIs, and containerized apps.
- Compression Support: Built-in gzip and Brotli compression reduces file sizes and speeds up loading.
- Caching: Nginx caches static content to avoid repeated disk reads.
- Scalability: Nginx efficiently manages large numbers of concurrent connections, making it ideal for high-traffic websites.