What is YAML?
YAML (YAML Ain't Markup Language) is a human-readable data serialization language. It's commonly used for configuration files and in applications where data is being stored or transmitted. Docker uses YAML for Docker Compose files.
YAML Basics:
- Uses indentation to represent structure (spaces, not tabs)
- Case sensitive
- File extension is typically .yml or .yaml
- Supports comments starting with #
- Uses key-value pairs separated by a colon
Basic YAML Structure
name: "John Doe" age: 30 is_student: false hobbies: - "reading" - "hiking" - "coding" address: street: "123 Main St" city: "Anytown" zip: 12345
Explanation:
- Key-value pairs separated by colons
- Lists (arrays) are represented with hyphens
- Nested objects use indentation
- Strings can be quoted or unquoted
Docker Compose Example
# Docker Compose file version version: '3.8' # Define services (containers) services: # Web service using nginx web: image: nginx:latest ports: - "80:80" volumes: - ./html:/usr/share/nginx/html # Database service using PostgreSQL database: image: postgres:13 environment: POSTGRES_DB: "mydb" POSTGRES_USER: "user" POSTGRES_PASSWORD: "password" volumes: - db_data:/var/lib/postgresql/data # Define volumes volumes: db_data:
Explanation:
- Defines multiple services that work together
- Specifies container images and configurations
- Maps ports between host and containers
- Sets environment variables
- Defines volumes for data persistence
Dockerfile Basics
A Dockerfile is a text document that contains all the commands a user could call on the
command line to assemble an image. Using docker build, users can create an automated build
that executes several command-line instructions in succession.
Sample Dockerfile for Node.js Application:
# Use an official Node.js runtime as a base image FROM node:18-alpine # Set the working directory in the container WORKDIR /app # Copy package.json and package-lock.json (if available) COPY package*.json ./ # Install dependencies RUN npm install # Copy the rest of the application code COPY . . # Make port 3000 available to the world outside this container EXPOSE 3000 # Define environment variable ENV NODE_ENV=production # Run the application when the container launches CMD ["npm", "start"]
Common Dockerfile Instructions:
- FROM → Sets the base image
- RUN → Executes commands
- COPY → Copies files from host to container
- WORKDIR → Sets the working directory
- EXPOSE → Documents which ports the container uses
- CMD → Provides default command for container
Building and Running:
docker build -t my-node-app .
docker run -p 4000:3000 my-node-app