Mục tiêu
Trong bài viết này chúng ta sẽ tiến hành cấu hình môi trường để deploy ứng dụng React với Nginx trong Docker
.
Tiến hành
1. Init project
Trước tiên để có thể deploy ứng dụng thì ta cần 1 project, ở đây mình sẽ bắt đầu với project cơ bản nhất của React.
1
npx create-react-app my-app
Sau khi init project xong, chúng ta sẽ có 1 cấu trúc dự án như sau
1
2
3
4
5
6
7
8
9
├── package.json
├── public
│ ├── ...
│ └── robots.txt
├── README.md
├── src
│ ├── ...
│ └── App.js
└── yarn.lock
2. Setup Docker
Tiếp đó ta thêm 1 vài file config sau
1
2
3
4
5
6
7
8
9
10
11
12
13
14
+ ├── docker-compose.yml
+ ├── Dockerfile
+ ├── .dockerignore
+ ├── .nginx
+ │ └── nginx.conf
├── package.json
├── public
│ ├── ...
│ └── robots.txt
├── README.md
├── src
│ ├── ...
│ └── App.js
└── yarn.lock
2.1. .dockerignore
Nó sẽ ignore các file chúng ta không muốn copy vào trong image, từ đó giúp cho giảm kích thước của image tối đa.
1
2
3
4
5
6
7
node_modules
npm-debug.log
build
.dockerignore
**/.git
**/.DS_Store
**/node_modules
2.2. Folder .nginx
Đây sẽ folder để config nginx
File nginx.conf
listen 80
:nginx
sẽ listen port 80 trong container để hiển thị app.try_files
: Đối với React sẽ là single page, tức là chỉ có 1 route duy nhất để hiển thị toàn bộ app. Với thứ tựtry_files
như trên nginx sẽ duyệt lần lượt theo thứ tự$uri > /index.html > 404(not found page)
để kiểm tra, nếu k hợp lệ thì sẽ chuyển đến route tiếp theo để kiểm tra và hiển thị.error_page
: một vào route lỗi hiển thị mặc định.
2.3. File Dockerfile
2.4. Folder docker-compose.yml
Để đơn giản cho việc run Docker và tích hợp với nhiều service khác, ta sẽ viết thêm docker-compose.yml
3. Run Docker
- Start container
Sau khi run xong chúng ta xem ứng dụng ở http://localhost:3000
- Stop container
3. Tổng kết
Trên đây là hướng dẫn cấu hình để triển khai 1 ứng dụng React, Nginx trong Docker
.
Các bạn có thể xem code tại đây github