“Code chạy được chưa?”
“Chạy rồi mà trong máy em!”
👉 Docker: “Để tao lo!”
🧠 Mục tiêu
Biến bạn từ một người từng docker ps
xong đứng hình thành kẻ có thể:
- Build image như đầu bếp Michelin
- Chạy container như khởi động Iron Man
- Quản lý microservice không khác gì làm leader DevOps (ảo thôi =)))
📦 Docker là gì?
Docker là công cụ giúp bạn đóng gói app + mọi thứ nó cần vào trong 1 container
(kiểu như... hộp cơm Bento cho developer, có đủ thịt cá cơm rau).
- Docker Image: công thức nấu ăn
- Docker Container: món ăn đã nấu xong
- Dockerfile: cuốn sổ tay đầu bếp
🛠️ Cài Docker
🧑💻 Với macOS
- Truy cập: https://www.docker.com/products/docker-desktop/
- Tải về và cài đặt
Kiểm tra:
docker --version
🐧 Với Linux (Ubuntu demo nha)
```bash
sudo apt update
sudo apt install docker.io -y
sudo systemctl start docker
sudo systemctl enable docker
# Cho user hiện tại quyền chạy docker không cần sudo
sudo usermod -aG docker $USER
newgrp docker
```
🪟 Với Windows
- Tải Docker Desktop
- Bật WSL2 trong settings
- Cài xong thì khởi động lại máy (cho phong thuỷ)
📄 Dockerfile – Bắt đầu container hoá
Tạo file Dockerfile
:
```Dockerfile
FROM ruby:3.2
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
WORKDIR /app
COPY . /app
RUN bundle install
CMD ["rails", "server", "-b", "0.0.0.0"]
```
🧑🍳 Build image
```bash
docker build -t my-ruby-app .
```
-t
: đặt tên image.
: build từ thư mục hiện tại
Quên dấu .
là Docker bối rối luôn đó
🚀 Chạy container
```bash
docker run -it --rm -p 3000:3000 my-ruby-app
```
-it
: mode tương tác--rm
: chạy xong xoá luôn (đỡ rác)-p
: map cổng
Truy cập: http://localhost:3000
🔥 Docker Compose – Dành cho team container
Tạo file docker-compose.yml
:
```yaml
version: '3'
services:
db:
image: postgres
environment:
POSTGRES_USER: dev
POSTGRES_PASSWORD: secret
web:
build: .
command: rails server -b 0.0.0.0
volumes:
- .:/app
ports:
- "3000:3000"
depends_on:
- db
```
Chạy bằng:
```bash
docker-compose up
```
🕵 Debug nhanh
Vào container:
```bash
docker exec -it <container_id> bash
```
Xem log:
```bash
docker logs <container_id>
```
Danh sách container:
```bash
docker ps
```
🧠 Tips sống còn
- Volume là chìa khoá để live reload khi dev
Nếu build chậm, thử dọn cache:
docker builder prune
Xoá mọi thứ không dùng tới:
docker system prune -a
🐒 Tấu hài cuối bài
Người ta hỏi: “Docker là gì?”
Dev: “Là thứ khiến máy em chạy được, máy anh thì không.”
Docker: “Ghim câu đó lên CV giùm em nha.”
📚 Tài liệu thêm
🎁 Bonus: Hello Docker!
```bash
mkdir docker-demo && cd docker-demo
echo "puts 'Hello from Docker!'" > app.rb
echo -e "FROM ruby\nCOPY . /app\nWORKDIR /app\nCMD [\"ruby\", \"app.rb\"]" > Dockerfile
docker build -t hello-docker .
docker run hello-docker
```
🫡 Bạn đã chính thức container hoá! Giờ lên LinkedIn viết:🛳️ Dev biết dùng Docker từ 2025
– xịn xò liền.