Step 1: Set Up Project Directory/Folder Create a directory for your project files.
mkdir myapp
cd myapp
Step 2: Create Application (Example: Simple Node.js App) Create a server.js file for a basic web server. you can use vs code.
// server.js
const http = require('http');
const port = 3000;
http.createServer((req, res) => res.end('Hello from Docker!')).listen(port);
Step 3: Create package.json This file manages dependencies for Node.js. Create it in the same directory as server.js.
{
"name": "myapp",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
}
}
Step 4: Create Dockerfile In the same directory (all file create same folder), create a file called Dockerfile with the following contents:
# Use the official Node.js base image
FROM node:14
# Set the working directory inside the container
WORKDIR /usr/src/app
# Copy package.json and install dependencies
COPY package*.json ./
RUN npm install
# Copy the rest of the application files
COPY . .
# Expose the app's port
EXPOSE 3000
# Run the app
CMD ["npm", "start"]
Step 5: Build Docker Image In your terminal (Command Prompt or Terminal or VS Code Terminal), run:
docker build -t myapp .
Step 6: Run the Docker Container Run the container using the following command:
docker run -p 3000:3000 myapp
Step 7: View the Result Open your browser and go to http://localhost:3000. You should see:
Hello from Docker!