{"id":28511628,"url":"https://github.com/akashdeep023/mern-ec2-docs","last_synced_at":"2026-02-11T11:33:34.962Z","repository":{"id":296086616,"uuid":"992206643","full_name":"akashdeep023/mern-ec2-docs","owner":"akashdeep023","description":"A step-by-step guide to deploying a MERN (MongoDB, Express.js, React, Node.js) stack application on an AWS EC2 instance.","archived":false,"fork":false,"pushed_at":"2025-06-03T22:15:01.000Z","size":11,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-20T01:17:35.189Z","etag":null,"topics":["aws","aws-ec2","deploy","mern-stack","nginx","pm2","private-repository"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/akashdeep023.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-05-28T19:34:30.000Z","updated_at":"2025-08-09T22:06:32.000Z","dependencies_parsed_at":"2025-05-28T23:19:25.331Z","dependency_job_id":null,"html_url":"https://github.com/akashdeep023/mern-ec2-docs","commit_stats":null,"previous_names":["akashdeep023/mern-ec2-docs"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/akashdeep023/mern-ec2-docs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdeep023%2Fmern-ec2-docs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdeep023%2Fmern-ec2-docs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdeep023%2Fmern-ec2-docs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdeep023%2Fmern-ec2-docs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/akashdeep023","download_url":"https://codeload.github.com/akashdeep023/mern-ec2-docs/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdeep023%2Fmern-ec2-docs/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29332589,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-11T06:13:03.264Z","status":"ssl_error","status_checked_at":"2026-02-11T06:12:55.843Z","response_time":97,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","aws-ec2","deploy","mern-stack","nginx","pm2","private-repository"],"created_at":"2025-06-09T00:07:37.565Z","updated_at":"2026-02-11T11:33:34.928Z","avatar_url":"https://github.com/akashdeep023.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# **MERN EC2 Docs**\n\n_**A step-by-step guide to deploying a MERN (MongoDB, Express.js, React, Node.js) stack application on an AWS EC2 instance.**_\n\n---\n\n## 🧰 **Prerequisites**\n\n-   AWS account\n-   Basic knowledge of Terminal Ubuntu, and Linux\n-   A MERN stack project (client \u0026 server folders)\n-   Domain name\n-   GitHub repo access (if deploying via Git)\n\n---\n\n## 🔑 **Create AWS Account**\n\n1. Sign up at the [AWS Cloud](https://aws.amazon.com/free)\n2. Choose: **Business** account type (recommended)\n3. Account Name: Any (does **not** need to match your project name)\n4. Payment Method: Use a **Credit Card** (some **Debit Cards** may work)\n5. Fill in required personal or business details\n6. Complete identity verification (email/phone)\n7. Log into the console once your account is active\n\n---\n\n## 🖥️ **Launch EC2 Instance**\n\n1. In the AWS Console, search for and open the **EC2** service\n2. Go to: **EC2 \u003e Instances \u003e Launch Instance**\n3. Enter instance name: e.g., `mern-server` or your project name\n4. Choose an Amazon Machine Image (AMI):\n    - **Ubuntu Server 22.04 LTS** (Recommended)\n5. Choose Instance Type:\n    - **t2.micro** (Free Tier eligible)\n6. Create or select a key pair:\n    - **Key pair type:** RSA\n    - **Private key format:** `.pem`\n    - Save the `.pem` file securely (you’ll need it to SSH)\n7. Configure other settings as needed (default is usually fine)\n8. Click **Launch Instance**\n9. Wait a few moments and check the instance status:\n    - **Instance state:** Running\n    - **Status check:** 2/2 checks passed ✅\n\n---\n\n## 🔐 Connect to EC2 via SSH\n\n1. Go to the **EC2 \u003e Instances** page\n2. Find your running instance and click on the **Instance ID**\n3. On the top-right, click the **Connect** button\n4. Choose the **SSH Client** tab (used for terminal access)\n\n---\n\n## 🧭 Steps to Connect Using Terminal\n\n1. **Open an SSH client** (Terminal on macOS/Linux, or PowerShell on Windows)\n2. **Locate your private key file**  \n   The key used to launch this instance is:  \n   `aws-instance-login.pem`\n3. **Set the correct permission** for your `.pem` file:\n\n    ```bash\n    # Run this command once to set the correct permission for your PEM file\n    chmod 400 \"aws-instance-login.pem\"\n    ```\n\n4. **Connect to your instance using its Public DNS**  \n   Example Public DNS:  \n   `ec2-00-0-000-000.ap-south-1.compute.amazonaws.com`\n\n5. 🖥️ **Example SSH Command**  \n   To connect to your EC2 instance, you must use it like this:\n\n    ```bash\n    # Connect to your EC2 instance using this command:\n    ssh -i \"aws-instance-login.pem\" ubuntu@ec2-00-0-000-000.ap-south-1.compute.amazonaws.com\n    ```\n\n    \u003e ✅ Make sure you’re in the directory where your `.pem` file is saved\n\n    \u003e ✅ Replace the DNS with your actual `EC2 Public DNS`\n\n    \u003e ✅ Use `ubuntu@` for Ubuntu instances, or `ec2-user@` for Amazon Linux\n\n    \u003e ✅ If successful, you'll be logged into your EC2 instance via the terminal.\n\n---\n\n## ⚙️ Install Node.js and NVM\n\n1. Go to [Node.js Downloads](https://nodejs.org/en/download)\n2. Select the exact Node.js version your project uses\n3. Since we're using **Ubuntu**, choose the **macOS/Linux** tab\n4. Choose the **nvm** installation option\n5. This will also install **npm** (Node Package Manager)\n6. Install NVM and Node.js Command\n\n    ```bash\n    # Download and install NVM:\n    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash\n\n    # Load NVM into current shell (without restarting terminal):\n    \\. \"$HOME/.nvm/nvm.sh\"\n\n    # Install Node.js (version 23 in this case):\n    nvm install 23\n    ```\n\n7. Verify Installations Command\n\n    ```bash\n    # Check npm version:\n    npm -v   # Should print \"10.9.2\"\n\n    # Check Node.js version:\n    node -v  # Should print \"v23.11.1\"\n    nvm current  # Should print \"v23.11.1\"\n    ```\n\n    \u003e 📌 Make sure you're connected to the internet when running these commands.\n\n    \u003e 📌 You can change the Node.js version later using `nvm install \u003cversion\u003e` or `nvm use \u003cversion\u003e`\n\n8. Exit from your EC2 Instance (Virtual Machine)\n\n    ```bash\n    exit\n    ```\n\n9. Reconnect to your EC2 Instance using Terminal\n\n    ```bash\n    ssh -i \"aws-instance-login.pem\" ubuntu@ec2-00-0-000-000.ap-south-1.compute.amazonaws.com\n    ```\n\n---\n\n## 🗃️ **Clone Your MERN Project**\n\n### 📂 **Clone Public Repositories on EC2**\n\n1. Frontend Repository\n\n    ```bash\n    git clone https://github.com/your-username/frontend-repo.git\n    ```\n\n2. Backend Repository\n\n    ```bash\n    git clone https://github.com/your-username/backend-repo.git\n    ```\n\n3. Verify Cloned Repo\n\n    ```bash\n    ls\n    ```\n\n---\n\n### 🔐 **Clone Private Repositories on EC2**\n\n\u003cdetails\u003e\n  \u003csummary\u003eClick to view full instructions\u003c/summary\u003e\n\n#### 1. ✅ Configure Git to Store Credentials\n\n```bash\ngit config --global credential.helper store\n```\n\n\u003e This stores your credentials locally so you don’t need to enter them every time (⚠️ not recommended for production environments).\n\n---\n\n#### 2. 🔑 Generate a GitHub Personal Access Token (PAT)\n\n1. Go to [**GitHub → Settings → Developer settings → Personal access tokens**](https://github.com/settings/tokens)\n2. Click **\"Fine-grained tokens\"** or **\"Tokens (classic)\"**\n3. Click **Generate new token**\n4. Set the **expiration date** and **name**\n5. Enable the required scopes (for private repo access, enable at least: `repo`)\n6. Click **Generate token**\n7. Copy the token **immediately** — you won’t see it again!\n\n#### 3. 📥 Clone the **Private Repository**\n\n1.  Frontend Repository\n\n    ```bash\n    git clone https://\u003cusername\u003e:\u003cyour-token\u003e@github.com/\u003cusername\u003e/\u003cfrontend-repo\u003e.git\n    ```\n\n2.  Backend Repository\n\n    ```bash\n    git clone https://github.com/your-username/backend-repo.git\n    ```\n\n#### 4. 📂 Verify Cloned Repo\n\n```bash\nls\n```\n\n#### ⚠️ Security Warning\n\n-   **Do not share or commit your token in code**\n-   For production or shared servers, use **SSH keys** or **GitHub CLI**\n\n\u003c/details\u003e\n\n---\n\n## ⚙️ Install Nginx and PM2\n\n**Update Ubuntu package list**\n\n```bash\nsudo apt update\n```\n\n\u003e This command refreshes the list of available packages and their versions.\n\n\u003e It's recommended to run before installing any new software.\n\n### Nginx Commands\n\n1.  Install Nginx to deploy our project\n\n    ```bash\n    sudo apt install nginx\n    ```\n\n2.  Start Nginx\n\n    ```bash\n    sudo systemctl start nginx\n    ```\n\n3.  Enable Nginx on boot\n\n    ```bash\n    sudo systemctl enable nginx\n    ```\n\n4.  Restart Nginx\n\n    ```bash\n    sudo systemctl restart nginx\n    ```\n\n### PM2 Commands\n\n1.  Install PM2 to run our server 24X7\n\n    ```bash\n    npm install pm2 -g\n    ```\n\n2.  Start the server with PM2\n\n    ```bash\n    pm2 start npm -- start # pm2 start (run pm2 server), npm start (project start command)\n    pm2 start npm --name \"backend\" -- start # or with a custom name\n    ```\n\n3.  Check server logs\n\n    ```bash\n    pm2 logs\n    ```\n\n4.  Remove (flush) PM2 server logs\n\n    ```bash\n    pm2 flush \u003cpm2-server-name\u003e # by name\n    # or\n    pm2 flush \u003cpm2-server-id\u003e # by id\n    ```\n\n5.  View all list of PM2 server\n\n    ```bash\n    pm2 list # show all start server\n    ```\n\n6.  Stop pm2 server\n\n    ```bash\n    pm2 stop \u003cpm2-server-name\u003e # by name\n    # or\n    pm2 stop \u003cpm2-server-id\u003e # by id\n    ```\n\n7.  Restart pm2 server\n\n    ```bash\n    pm2 restart \u003cpm2-server-name\u003e # by name\n    # or\n    pm2 restart \u003cpm2-server-id\u003e # by id\n    ```\n\n8.  Delete pm2 server\n\n    ```bash\n    pm2 delete \u003cpm2-server-name\u003e # by name\n    # or\n    pm2 delete \u003cpm2-server-id\u003e # by id\n    ```\n\n9.  Custom name of pm2 server\n\n    ```bash\n    pm2 start npm --name \"backend\" -- start\n    ```\n\n---\n\n## 🌐 **Setup Frontend (React) with Nginx on AWS EC2**\n\n1.  Navigate to the Frontend Project\n\n    ```bash\n    cd frontend-repo\n    ```\n\n2.  Install Dependencies \u0026 Build the Project\n\n    ```bash\n    npm install\n    npm run build\n    ```\n\n    \u003cdetails\u003e\n\n    \u003csummary\u003e⚠️ Build failed? Click to view memory fix instructions.\n\n    If the build fails due to memory limitations (common on small EC2 instances), follow these steps to add a swap file:\u003c/summary\u003e\n\n    1.  Check Available Memory\n\n        ```bash\n        free -h\n        ```\n\n    2.  Create \u0026 Enable Swap File (2GB)\n\n        ```bash\n        sudo dd if=/dev/zero of=/swapfile bs=1M count=2048\n        sudo mkswap /swapfile\n        sudo swapon /swapfile\n        echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab\n        ```\n\n    3.  Confirm Swap is Active\n\n        ```bash\n        sudo swapon --show\n        free -h\n        ```\n\n    4.  Retry Build with Increased Memory Allocation\n\n        ```bash\n        NODE_OPTIONS=\"--max-old-space-size=4096\" npm run build\n        ```\n\n       \u003c/details\u003e\n\n3.  Setup `.env` File\n\n    -   Create `.env` file:\n\n        ```bash\n        sudo nano .env\n        ```\n\n    -   Paste it all your frontend environment variables\n\n        ```bash\n        # Example environment variables\n        BACKEND_URL=/api\n        ```\n\n        \u003e Save and Exit\n\n4.  Deploy Build Files to Nginx Directory\n\n    ```bash\n    # Start \u0026 Enable Nginx\n    # copy code from build to Nginx web root\n    sudo scp -r build/* /var/www/html/ # dist\n    ```\n\n    \u003e **Note**: Make sure `/var/www/html/` is empty or only contains files from your intended deployment.\n\n5.  Enable HTTP Access on Port 80 (in AWS EC2)\n\n    -   Before accessing your frontend in the browser, make sure port 80 is open on your instance:\n\n    1. Go to the **EC2 \u003e Instances** page\n    2. Find your running instance and click on the **Instance ID**\n    3. GO the **Security** tab\n    4. Click on the linked **Security groups**\n    5. Under **Inbound rules**, click **Edit Inbound Rules**\n    6. Add a rule:\n        - Type `HTTP`\n        - Port `80`\n        - Source `0.0.0.0/0` (for public access)\n    7. Click **Save rules**\n\n6.  Your Frontend is Now Live!\n\n    -   Open your browser and go to:\n\n        ```bash\n        http://\u003cyour-ec2-ip\u003e/\n        # or\n        http://domain.com/\n        ```\n\n---\n\n## 🌍 **Setup Backend (Node + Express) on AWS EC2**\n\n1. Navigate to the Backend Project\n\n    ```bash\n    cd backend-repo\n    ```\n\n2. Install Dependencies\n\n    ```bash\n    npm install\n    ```\n\n3. Whitelist EC2 IP in MongoDB Atlas\n\n    - Go to [MongoDB Atlas](https://www.mongodb.com/)\n    - Navigate to **Network Access** -\u003e Add IP Address\n    - Add your EC2 public IP address or use `0.0.0.0/0` (for open access)\n\n4. Setup `.env` File\n\n    - Create `.env` file:\n\n        ```bash\n        sudo nano .env\n        ```\n\n    - Paste it all your backend environment variables\n\n        ```bash\n        # Example environment variables\n        PORT=7777\n        MONGO_DB=mongodb+srv://username:password@cluster.mongodb.net/dbname\n        ```\n\n        \u003e Save and Exit\n\n5. Start the backend server with PM2\n\n    ```bash\n    pm2 start npm --name \"backend\" -- start\n    ```\n\n    \u003e This keeps your server running in the background, even after SSH disconnects.\n\n6. Configure Nginx to Reverse Proxy to Node.js\n\n    - Open the Nginx default config:\n\n        ```bash\n        sudo nano /etc/nginx/sites-available/default\n        ```\n\n    - Replace or update the contents with:\n\n        ```bash\n        # ...\n        # Add searver name and location\n        server_name 00.0.000.000; # Domain Name or Instance IP Address\n        location /api/ {\n                proxy_pass http://localhost:7777/;  # (PORT - 7777) Pass the request to the Node.js app\n                proxy_http_version 1.1;\n                proxy_set_header Upgrade $http_upgrade;\n                proxy_set_header Connection 'upgrade';\n                proxy_set_header Host $host;\n                proxy_cache_bypass $http_upgrade;\n        }\n        # Correctly redirects all unknown (404) routes to index.html\n        location / {\n                # First attempt to serve request as file, then\n                # as directory, then fall back to displaying a 404.\n                # try_files $uri $uri/ =404;\n                try_files $uri /index.html;\n        }\n        # ...\n        ```\n\n7. Save and Exit\n\n    - Press `CTRL + O`, Enter to save\n    - Press `CTRL + X` to exit\n\n8. Restart Nginx\n\n    ```bash\n     sudo systemctl restart nginx\n    ```\n\n9. Enable HTTP Access on Port `7777` (in AWS EC2)\n\n    - Before accessing your backend in the browser, make sure port `7777` is open on your instance:\n\n    1. Go to the **EC2 \u003e Instances** page\n    2. Find your running instance and click on the **Instance ID**\n    3. GO the **Security** tab\n    4. Click on the linked **Security groups**\n    5. Under **Inbound rules**, click **Edit Inbound Rules**\n    6. Add a rule:\n        - Type `HTTP`\n        - Port `7777`\n        - Source `0.0.0.0/0` (for public access)\n    7. Click **Save rules**\n\n10. Your Backend is Now Live!\n\n    - You can now access your backend API via:\n\n        ```bash\n        http://\u003cyour-ec2-ip\u003e/api/\n        # or\n        http://domain.com/api/\n        ```\n\n---\n\n## 🧯 **Troubleshooting**\n\n-   If it doesn't load, make sure:\n\n    -   **Nginx is running** `sudo systemctl status nginx`\n    -   **Your build files** correctly copied to `/var/www/html`\n    -   **Port not open?** Check AWS Security Groups\n    -   **App crashing?** Run `pm2 logs`\n    -   **Server can't connect to MongoDB Atlas?** Check IP whitelisting\n\n---\n\n## ✅ **Done!**\n\nYour MERN stack is now live on AWS EC2. 🎉\n\n```bash\nhttp://\u003cyour-ec2-ip\u003e\n#or\nhttp://domain.com\n```\n\n---\n\n## Redploy MERN Project\n\n### Backend \u0026 Frontend Repo Redeploy Guide\n\n#### Frontend Repository\n\n1. Navigate to the Frontend Project\n\n    ```bash\n    cd frontend-repo\n    ```\n\n2. Pull latest code \u0026 Install dependencies\n    ```bash\n    git pull\n    npm install\n    ```\n3. Build the project (with extended memory if needed)\n\n    ```bash\n    npm run build\n    #or\n    NODE_OPTIONS=\"--max-old-space-size=4096\" npm run build\n    ```\n\n4. Deploy Build Files to Nginx Directory\n\n    ```bash\n    sudo scp -r build/* /var/www/html/ # dist\n    ```\n\n#### Backend Repository\n\n1. Navigate to the Backend Project\n\n    ```bash\n    cd backend-repo\n    ```\n\n2. Pull latest code \u0026 Install dependencies\n\n    ```bash\n    git pull\n    npm install\n    ```\n\n3. Restart the PM2 server\n\n    ```bash\n    pm2 restart \u003cpm2-server-name\u003e # by name\n    # or\n    pm2 restart \u003cpm2-server-id\u003e # by id\n    ```\n\n## 📎 **Resources**\n\n-   [MongoDB Atlas](https://www.mongodb.com/)\n-   [Node.js Docs](https://nodejs.org/en)\n-   [PM2 Docs](https://pm2.keymetrics.io/)\n-   [Nginx Config Reference](https://nginx.org/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakashdeep023%2Fmern-ec2-docs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fakashdeep023%2Fmern-ec2-docs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakashdeep023%2Fmern-ec2-docs/lists"}