Building Custom Docker Images
A Dockerfile defines the steps to build a custom Docker image for your application.
Dockerfile Basics
# Start from a base image
FROM ubuntu:22.04
# Set environment variables
ENV DEBIAN_FRONTEND=noninteractive
# Run commands during build
RUN apt update && apt install -y nginx && apt clean
# Copy files from host into image
COPY ./html /var/www/html
# Set the working directory
WORKDIR /app
# Expose a port (documentation only)
EXPOSE 80
# Command to run when container starts
CMD ["nginx", "-g", "daemon off;"]
Build the Image
docker build -t myapp:1.0 .
docker build -t myapp:latest -f Dockerfile.prod .
Run Your Custom Image
docker run -d -p 80:80 myapp:1.0
Multi-Stage Builds (Smaller Production Images)
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
The final image contains only Nginx + the built files, not Node.js or build tools.
.dockerignore File
Like .gitignore but for Docker builds. Prevents large or sensitive files from being copied into the image:
node_modules
.git
*.log
.env
Push to Docker Hub
docker login
docker tag myapp:1.0 yourusername/myapp:1.0
docker push yourusername/myapp:1.0