🎯 What We’ll Cover
- Setting up a basic Node.js app
- Writing a
Dockerfile - Running it in a container
- Making it accessible to the outside world
By the end, you’ll have a containerized Node.js app that works like magic (minus the wizard robes).
📦 Step 1: Create a Basic Node.js App
First, let’s set up a super simple Node.js application.
Run these commands:
| |
Now, let’s install Express (because who writes plain HTTP servers anymore?):
| |
Then, create a file called server.js and paste this inside:
| |
Boom!
Basic Node.js server ✅
🛠 Step 2: Write the Dockerfile
Now, let’s create a Dockerfile.
This file tells Docker how to build our container.
Create a file named Dockerfile (yes, no extension) and add this:
| |
This file does a few things:
- Uses a small, efficient Node.js image (
node:18-alpine) - Sets up a working directory
- Copies
package.jsonand installs dependencies - Copies the rest of the files
- Exposes port
3000 - Runs the app with
node server.js
🏗 Step 3: Build and Run the Docker Container
Now that we have a Dockerfile, let’s build our image and run it.
🔨 Build the Image
| |
This tells Docker to build an image named my-node-app using the Dockerfile in the current directory (.).
�� Run the Container
| |
Here’s what’s happening:
-p 3000:3000maps port 3000 inside the container to port 3000 on your machine.my-node-appis the name of the image we just built.
Now, visit http://localhost:3000/, and you should see:
| |
🐳 Extra: Running in Detached Mode
If you want the container to run in the background (so your terminal isn’t stuck), run:
| |
Then, to stop the container later, use:
| |
📌 Key Ideas
| Concept | Summary |
|---|---|
| Dockerfile | Defines how to build the Node.js container |
| docker build | Builds the image from the Dockerfile |
| docker run | Runs the container and exposes the port |
| Detached Mode | Allows the container to run in the background |
| Port Mapping | Maps the container’s port to the host machine |
