DevOps

Building and Managing Docker Images Locally

Introduction

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

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"]

Ready to transform your business with our technology solutions? Contact Us  today to Leverage Our DevOps Expertise. 

Contact Us

0

Comment

221

Share

facebook
LinkedIn
Twitter
Mail
Devops

Related Center Of Excellence