Hello again! In Day 2, we installed Docker and ran pre-built containers. Today, we’ll create a simple app, build a Docker image, and manage it locally. We’ll use Node.js for our example app. Let’s build something!
Step 1: Create a Sample App
Create a directory my-app
and add these files:
server.js
:
const http = require('http');
const hostname = '0.0.0.0';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
package.json
:
{
"name": "my-app",
"version": "1.0.0",
"main": "server.js",
"dependencies": {
"http": "^0.0.1-security"
}
}
Step 2: Write a Dockerfile
In my-app
, create Dockerfile
:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
This uses a base Node image, copies files, installs deps, and runs the server.
Step 3: Build and Run the Image
Build: docker build -t my-app .
Run: docker run -d -p 3000:3000 my-app
Visit http://localhost:3000—see "Hello, World!"
Step 4: Managing Images
- List:
docker images
- Remove:
docker rmi my-app
- Multi-stage build example (for optimization):
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build # If applicable
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app .
CMD ["node", "server.js"]
Today’s Takeaway
You’ve built and run a custom Docker image! Next, we move to AWS.
What’s Next?
In Day 4, we’ll set up an AWS account and IAM basics.
Top comments (0)