News Photo

How to Initiate a Laravel Project via Docker Compose

1. Set Up Your Project Directory

  • Create a new directory for your Laravel project:


    mkdir my-laravel-project
    cd my-laravel-project

2. Create Docker Compose File

  • Inside your project directory, create a docker-compose.yml file with the following content:

    version: '3'
    services:
    laravel-app:
    build:
    context: .
    dockerfile: Dockerfile
    image: laravel-test-app
    ports:
    - '8000:8000'
    volumes:
    - .:/var/www/html
    depends_on:
    - db
    environment:
    - APP_NAME=Laravel
    - APP_ENV=development
    - DB_HOST=db
    - DB_DATABASE=laravel
    - DB_USERNAME=root
    - DB_PASSWORD=secret

    networks:
    - mynetwork

    db:
    image: mysql:8.0
    ports:
    - '3307:3306'
    environment:
    - MYSQL_DATABASE=laravel
    - MYSQL_ROOT_PASSWORD=secret
    networks:
    - mynetwork

    networks:
    mynetwork:

3. Create a Dockerfile for Laravel

  • Create a Dockerfile in the same directory with the following content:


    FROM php:8.1-fpm

    # Set working directory
    WORKDIR /var/www/html

    # Install dependencies
    RUN apt-get update && apt-get install -y \
    build-essential \
    libpng-dev \
    libjpeg62-turbo-dev \
    libfreetype6-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    curl \
    unzip \
    git \
    && docker-php-ext-configure gd \
    --with-freetype \
    --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath opcache \
    && pecl install xdebug \
    && docker-php-ext-enable xdebug

    # Install Composer
    COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

    # Copy existing application directory contents
    COPY . /var/www/html

    # Copy existing application directory permissions
    COPY --chown=www-data:www-data . /var/www/html

    # Expose port 8000 and start the server
    EXPOSE 8000
    CMD php artisan serve --host=0.0.0.0 --port=8000

4. Build and Run the Containers

  • Now, you can build and run the Docker containers:


    docker-compose up -d --build

5. Install Laravel

  • Enter the app container:


    docker exec -it laravel_app bash
  • Once inside the container, install Laravel via Composer:


    composer create-project --prefer-dist laravel/laravel .

6. Configure Environment

  • After Laravel is installed, update the .env file in the root of your project to match the database configuration:


    DB_CONNECTION=mysql DB_HOST=db DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=laravel DB_PASSWORD=laravel

7. Run Migrations

  • Run the Laravel migrations to set up the database:


    php artisan migrate

8. Access Your Application

  • Your Laravel application should now be accessible at http://localhost:8000.

Contact for support 

  •  +8801812161440
  •  

    Share This News

    Comment

    Do you want to get our quality service for your business?