在Linux上使用Docker容器化部署Laravel应用程序是一个常见的做法,因为它可以提供一致的开发、测试和生产环境。以下是一个基本的步骤指南,帮助你在Linux上使用Docker容器化部署Laravel应用程序。
在你的Laravel项目根目录下创建一个名为Dockerfile的文件,并添加以下内容:
# 使用官方PHP镜像作为基础镜像
FROM php:7.4-fpm
# 安装必要的扩展
RUN docker-php-ext-install pdo_mysql mbstring xml zip opcache
# 安装Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# 设置工作目录
WORKDIR /var/www/html
# 复制项目文件
COPY . /var/www/html
# 安装项目依赖
RUN composer install --no-interaction --prefer-dist
# 设置文件权限
RUN chown -R www-data:www-data /var/www/html
# 暴露端口
EXPOSE 9000
# 启动PHP-FPM服务
CMD ["php-fpm"]
在你的Laravel项目根目录下创建一个名为docker-compose.yml的文件,并添加以下内容:
version: '3'
services:
app:
build:
context: .
dockerfile: Dockerfile
image: laravel-app
container_name: laravel_app
restart: unless-stopped
tty: true
environment:
SERVICE_NAME: app
SERVICE_TAGS: dev
working_dir: /var/www/html
volumes:
- ./:/var/www/html
networks:
- laravel
nginx:
image: nginx:latest
container_name: nginx
restart: unless-stopped
tty: true
ports:
- "80:80"
volumes:
- ./:/var/www/html
- ./nginx.conf:/etc/nginx/conf.d/default.conf
networks:
- laravel
networks:
laravel:
driver: bridge
volumes:
laravel_app:
在你的Laravel项目根目录下创建一个名为nginx.conf的文件,并添加以下内容:
server {
listen 80;
server_name localhost;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass app:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
在项目根目录下运行以下命令来构建和启动容器:
docker-compose up -d --build
打开浏览器并访问http://localhost,你应该能够看到你的Laravel应用程序。
通过以上步骤,你已经成功地在Linux上使用Docker容器化部署了一个Laravel应用程序。这种方法不仅提供了环境一致性,还简化了部署和维护过程。