Контейнеризация веб-приложения
Пройдите весь процесс контейнеризации типичного веб-приложения, включая его клиентскую часть, серверную часть и базу данных.
«Контейнеризация веб-приложения» — бесплатный урок Docker & Kubernetes for Developers на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Docker & Kubernetes for Developers, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Docker & Kubernetes for Developers содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Containerizing Web Apps
Welcome to containerizing a web application! In this lesson, we'll walk through how to package a complete web application, including its frontend, backend, and database, into Docker containers.
This is a crucial step for modern development, enabling consistency across environments and simplifying deployment.
Web App Architecture
A typical web application usually consists of several components working together. For our example, we'll focus on a common three-tier architecture:
- Frontend: The user interface (e.g., React, Vue, Angular) that runs in the browser.
- Backend: The server-side logic (e.g., Node.js, Python Flask, Java Spring) that handles business logic and API requests.
- Database: Stores and manages application data (e.g., PostgreSQL, MySQL, MongoDB).
Backend: Node.js API
First, let's create a Dockerfile for a simple Node.js backend API. This file tells Docker how to build an image for our backend service.
We'll start with a base Node.js image, copy our application code, install dependencies, and define the command to run the server.
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
Frontend: React & Nginx
For our frontend, we'll use a multi-stage Dockerfile. This is a best practice for frontend applications, allowing us to build the app in one stage and then serve the static assets using a lightweight web server like Nginx in a separate, smaller stage.
This results in a much smaller final image.
FROM node:18-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:stable-alpine
COPY --from=builder /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Database: PostgreSQL Service
For the database, we don't need to write a Dockerfile. Instead, we can use an official image from Docker Hub, like PostgreSQL.
It's crucial to use a Docker volume to ensure our database data persists even if the container is removed or recreated. We'll define this when we use Docker Compose.
Orchestration with Compose
Now that we have Dockerfiles for our frontend and backend, and know we'll use an official image for our database, we need a way to define and run all these services together.
This is where Docker Compose comes in. It uses a YAML file (docker-compose.yml) to configure all our services, networks, and volumes.
version: '3.8'
services:
# Define your application services here
volumes:
# Define named volumes for data persistence
networks:
# Define custom networks for inter-service communication
Compose: Backend Service
Let's add our backend service to the docker-compose.yml file. We'll specify its build context (where its Dockerfile is), map ports, define environment variables for database connection, and set up a dependency on the database.
version: '3.8'
services:
backend:
build: ./backend # Path to backend Dockerfile
ports:
- "3000:3000"
environment:
DATABASE_URL: postgres://user:password@db:5432/mydb
depends_on:
- db # Ensure db starts before backend
networks:
- app-network
networks:
app-network:
driver: bridge # Custom network for app services
Compose: Frontend Service
Next, we add the frontend service definition. This service will also be built from its Dockerfile, expose port 80, and depend on the backend service to ensure it's available for API calls.
version: '3.8'
services:
# ... backend service definition ...
frontend:
build: ./frontend # Path to frontend Dockerfile
ports:
- "80:80"
depends_on:
- backend # Frontend needs backend to be ready
networks:
- app-network
networks:
app-network:
driver: bridge
Compose: Database Service
Finally, we define the database service. We'll use the official postgres image, set crucial environment variables for database setup, and most importantly, attach a named volume for data persistence.
version: '3.8'
services:
# ... backend and frontend definitions ...
db:
image: postgres:13-alpine # Use an official PostgreSQL image
environment:
POSTGRES_DB: mydb
POSTGRES_USER: user
POSTGRES_PASSWORD: password
volumes:
- db_data:/var/lib/postgresql/data # Mount named volume
networks:
- app-network
volumes:
db_data: # Define the named volume
networks:
app-network:
driver: bridge
Launching the App Stack
With our docker-compose.yml file complete, launching the entire application stack is incredibly simple. Navigate to the directory containing your docker-compose.yml file and run a single command:
docker compose up -d: Builds images (if needed), creates containers, networks, and volumes, and starts all services in detached mode (-d).docker compose down: Stops and removes all services, networks, and volumes defined in the file.
docker compose up -d
Compose Configuration Check
Consider the following docker-compose.yml snippet for a simple web application:
version: '3.8'
services:
web:
build: .
ports:
- "8000:8000"
depends_on:
- db
db:
image: postgres:latest
environment:
POSTGRES_DB: appdb
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:Which of the following statements about this configuration are TRUE?
Lesson Summary
In this lesson, we learned how to containerize a full web application stack using Docker. We covered creating Dockerfiles for frontend and backend services, using official images for databases, and orchestrating everything with Docker Compose. This approach simplifies development, deployment, and scaling of complex applications.
- Defined Dockerfiles for a multi-stage frontend and a backend service.
- Integrated a database using an official Docker image and a named volume.
- Orchestrated all services using a
docker-compose.ymlfile. - Learned to launch the entire application stack with a single command.
Часто задаваемые вопросы
Урок «Контейнеризация веб-приложения» бесплатный?
Да — полный текст урока «Контейнеризация веб-приложения» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Docker & Kubernetes for Developers, подпишись на CoddyKit PRO. Курс Docker & Kubernetes for Developers содержит 4 уроков всего.
Чему я научусь в уроке «Контейнеризация веб-приложения»?
Пройдите весь процесс контейнеризации типичного веб-приложения, включая его клиентскую часть, серверную часть и базу данных. Ты практикуешь Docker & Kubernetes for Developers с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Docker & Kubernetes for Developers?
Предыдущий опыт не требуется. Docker & Kubernetes for Developers на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Контейнеризация веб-приложения»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Docker & Kubernetes for Developers?
Да. Каждый урок Docker & Kubernetes for Developers включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Контейнеризация веб-приложения
- Оптимизация образов Docker
- Безопасность и практики для рабочей среды
- Многоэтапная сборка компактных рабочих образов