3.3 KiB
🚀 Simple Node.js Hello World (with Docker & Environment Variables)
Welcome to this beginner-friendly guide! This project is a "Hello World" web application built using Node.js and Express. It is designed to be easily configurable using a .env file and ready to run inside a Docker container.
🛠 Prerequisites
Before you begin, ensure you have the following installed on your computer:
- Node.js (Version 18 or higher recommended)
- Docker (To run the application in a container)
- A Code Editor (Like VS Code)
📁 Project Structure Explained
Here is what's inside this project and what each file does:
index.js: The "brain" of our app. It handles web requests and sends back a message..env: A configuration file for "secrets" or settings (like which port to use).package.json: A manifest file that lists the libraries our app needs to work.Dockerfile: A set of instructions for Docker on how to "package" this app into a container..dockerignore/.gitignore: Files that tell Docker and Git which files to ignore (likenode_moduleswhich can be very large).
⚙️ How to Configure
You can change how the app behaves without touching the code! Open the .env file:
PORT=3000
MESSAGE="Hello from Node.js with .env!"
- PORT: The "doorway" the app uses to listen for visitors. (Default: 3000)
- MESSAGE: The text that will appear when you visit the app in your browser.
🏃 Method 1: Running Locally (Without Docker)
Use this method if you just want to test the app quickly on your machine.
- Open your terminal (Command Prompt, Terminal, or PowerShell).
- Navigate to the project folder:
cd hello-world-node - Install dependencies:
npm install - Start the app:
npm start - View the app: Open your browser and go to
http://localhost:3000.
🐳 Method 2: Running with Docker (Recommended)
Docker packages the app so it runs exactly the same way on every computer.
Step 1: Build the Image
This creates a "package" of your application.
docker build -t hello-world-node .
Step 2: Run the Container
This starts the "package" and makes it live.
docker run -d -p 3000:3000 --env-file .env --name my-hello-app hello-world-node
Note: -d runs it in the background, -p 3000:3000 maps your computer's port to the container's port.
Step 3: See it in action
Open your browser and visit http://localhost:3000.
🧹 Cleaning Up
If you want to stop the Docker container:
- Stop the container:
docker stop my-hello-app - Remove the container:
docker rm my-hello-app - Remove the image (optional):
docker rmi hello-world-node
❓ Troubleshooting
- Port already in use: If you see an error about port 3000, change the
PORTin your.envfile or stop any other apps running on that port. - Docker not running: Make sure the Docker Desktop app is open and running.
- Can't find
npm: Ensure Node.js is installed correctly and added to your system's PATH.