Docker is a lightweight containerization platform that allows you to package applications along with their dependencies, ensuring consistent performance across different environments. This article walks you through how to use Docker to containerize and deploy a Yii framework application, streamlining both development and deployment processes.
In the root directory of your Yii project, create a file named Dockerfile and add the following content:
FROM php:7.4-fpm
WORKDIR /var/www
COPY composer.json .
RUN composer install
COPY . .
EXPOSE 80
CMD ["php", "-S", "0.0.0.0:80"]
This Dockerfile defines a PHP environment, installs project dependencies, sets the working directory, and specifies the command used to start the application.
Navigate to your project’s root directory in the terminal and run the following command to build the Docker image:
<span class="fun">docker build -t yii-app .</span>
This command creates a Docker image named yii-app based on the Dockerfile configuration.
Once the image is built, run the container with this command:
<span class="fun">docker run -p 8080:80 yii-app</span>
After running the container, you can access your Yii application at http://localhost:8080.
After verifying your application locally, you can deploy it to a remote server. First, push the built image to Docker Hub or a private registry. Then, on the remote server, execute the following commands:
Pull the image:
<span class="fun">docker pull <registry>/<namespace>/yii-app</span>
Run the container:
<span class="fun">docker run -p 80:80 <registry>/<namespace>/yii-app</span>
Replace
If your Yii project relies on services such as databases or caching systems, Docker Compose is a great way to manage multiple containers. In your project’s root directory, create a docker-compose.yml file like the one below:
version: '3'
services:
web:
build: .
ports:
- "8080:80"
volumes:
- ./:/var/www
Then run the following command to start your application:
<span class="fun">docker-compose up -d</span>
Docker Compose will automatically build the image and start all required containers, allowing your Yii app and its dependent services to run together seamlessly.
By containerizing your Yii framework application with Docker, you can simplify environment setup and maintain consistency across development, testing, and production. Whether you’re deploying a single container or orchestrating multiple services, Docker provides an efficient and scalable solution for Yii application deployment.