Docker Setup for Laravel

User
docker setup for nignix, adminer,php laravel
Assistant
To set up a Docker environment for Nginx, Adminer, PHP, and Laravel, you can use Docker Compose to manage multiple services like PHP, Nginx, MySQL (or another database), and Adminer. Here's a step-by-step guide.

### Step 1: Install Docker and Docker Compose
Make sure Docker and Docker Compose are installed on your system. You can follow instructions from [Docker's official website](https://docs.docker.com/get-docker/) for installation.

### Step 2: Laravel Project
If you don’t have a Laravel project yet, you can create one:

composer create-project --prefer-dist laravel/laravel my-laravel-app
cd my-laravel-app

### Step 3: Docker Compose Configuration
Create a `docker-compose.yml` file in your Laravel project root with the following configuration:

version: '3.8'

services:
  # Laravel app service with PHP
  app:
    image: php:8.2-fpm
    container_name: laravel-app
    working_dir: /var/www
    volumes:
      - ./:/var/www
    networks:
      - laravel

  # MySQL database service
  db:
    image: mysql:8.0
    container_name: mysql-db
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: laravel
      MYSQL_USER: laravel
      MYSQL_PASSWORD: laravel
    volumes:
      - dbdata:/var/lib/mysql
    ports:
      - 3306:3306
    networks:
      - laravel

  # Adminer service to manage database
  adminer:
    image: adminer
    container_name: adminer
    ports:
      - 8080:8080
    networks:
      - laravel

  # Nginx service
  webserver:
    image: nginx:alpine
    container_name: nginx
    working_dir: /var/www
    volumes:
      - ./:/var/www
      - ./docker/nginx/conf.d:/etc/nginx/conf.d
    ports:
      - "8081:80"
    networks:
      - laravel

volumes:
  dbdata:

networks:
  laravel:
    driver: bridge

### Step 4: Nginx Configuration

Create a directory for Nginx configuration inside your project:

mkdir -p docker/nginx/conf.d

Inside the `docker/nginx/conf.d` directory, create a file called `default.conf` with the following Nginx configuration:

server {
    listen 80;
    index index.php index.html;
    server_name localhost;
    root /var/www/public;

    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;
    }
}

### Step 5: Laravel `.env` Configuration

Update your `.env` file to match the database connection in the Docker setup:

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

### Step 6: Build and Start the Containers

Run the following commands to build and start the containers:

docker-compose up --build

### Step 7: Accessing Services

– **Laravel**: Visit `http://localhost:8081` to see your Laravel app.
– **Adminer**: Visit `http://localhost:8080` to manage your database. Login with the following:
– System: `MySQL`
– Server: `db`
– Username: `laravel`
– Password: `laravel`
– Database: `laravel`

### Step 8: Install Laravel Dependencies

You need to install Laravel dependencies inside the `app` container:

docker exec -it laravel-app bash
composer install

### Step 9: Laravel Storage and Cache

Make sure to set up permissions and cache correctly:

docker exec -it laravel-app bash
php artisan storage:link
php artisan config:cache
php artisan route:cache
php artisan view:cache

Now, your Docker setup should be running with Nginx, PHP, Adminer, and MySQL ready to serve your Laravel application!

User
for apache
Assistant
To set up a Docker environment for **Apache**, **Adminer**, **PHP**, and **Laravel**, you can modify the configuration to use Apache instead of Nginx. Here’s a step-by-step guide to configure Apache in your Docker environment.

### Step 1: Laravel Project
If you don’t have a Laravel project yet, you can create one using the following command:

composer create-project --prefer-dist laravel/laravel my-laravel-app
cd my-laravel-app

### Step 2: Docker Compose Configuration
Create a `docker-compose.yml` file in your Laravel project root directory with the following configuration:

version: '3.8'

services:
  # Laravel app service with PHP and Apache
  app:
    image: php:8.2-apache
    container_name: laravel-app
    working_dir: /var/www
    volumes:
      - ./:/var/www
      - ./docker/apache/vhost.conf:/etc/apache2/sites-enabled/000-default.conf
    ports:
      - "8081:80"
    networks:
      - laravel
    environment:
      APACHE_DOCUMENT_ROOT: /var/www/public
    depends_on:
      - db

  # MySQL database service
  db:
    image: mysql:8.0
    container_name: mysql-db
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: laravel
      MYSQL_USER: laravel
      MYSQL_PASSWORD: laravel
    volumes:
      - dbdata:/var/lib/mysql
    ports:
      - 3306:3306
    networks:
      - laravel

  # Adminer service to manage the database
  adminer:
    image: adminer
    container_name: adminer
    ports:
      - 8080:8080
    networks:
      - laravel

volumes:
  dbdata:

networks:
  laravel:
    driver: bridge

### Step 3: Apache Virtual Host Configuration

Create a directory for Apache configuration:

mkdir -p docker/apache

Inside the `docker/apache` directory, create a file named `vhost.conf` with the following Apache Virtual Host configuration:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/public

    <Directory /var/www/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # Disable .htaccess for performance reasons and add support for rewriting
    <FilesMatch "^.ht">
        Require all denied
    </FilesMatch>

    <Directory />
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

This configuration ensures that Apache serves your Laravel application from the `public` directory.

### Step 4: Laravel `.env` Configuration

Update your `.env` file to match the database connection for Docker:

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

### Step 5: Build and Start Docker Containers

Run the following command to build and start the containers:

docker-compose up --build

### Step 6: Accessing Services

– **Laravel App**: Visit `http://localhost:8081` to see your Laravel app running on Apache.
– **Adminer**: Visit `http://localhost:8080` to manage your MySQL database. Use the following credentials:
– System: `MySQL`
– Server: `db`
– Username: `laravel`
– Password: `laravel`
– Database: `laravel`

### Step 7: Install Laravel Dependencies

You will need to install Laravel dependencies inside the app container:

docker exec -it laravel-app bash
composer install

### Step 8: Laravel Storage and Cache

Make sure to set up permissions and cache:

docker exec -it laravel-app bash
php artisan storage:link
php artisan config:cache
php artisan route:cache
php artisan view:cache

Now, your Docker environment should be fully set up with **Apache**, **PHP**, **Adminer**, and **MySQL**, serving your **Laravel** application!

User
IlluminateDatabaseQueryException

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for db failed: No such host is known. (Connection: mysql, SQL: select table_name as `name`, (data_length + index_length) as `size`, table_comment as `comment`, engine as `engine`, table_collation as `collation` from information_schema.tables where table_schema = 'laravel' and table_type in ('BASE TABLE', 'SYSTEM VERSIONED') order by table_name)

Assistant
The error you're seeing, `SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for db failed: No such host is known`, indicates that the **Laravel application** cannot connect to the **MySQL database container**. This is typically caused by one of the following issues:

### Possible Causes:
1. **Database container name mismatch**: The MySQL container is referred to as `db` in your `docker-compose.yml` file. If the name is different in the `.env` file, it will result in a connection error.
2. **Database service is not running**: The database container (`mysql-db`) might not be up, or there may be issues during the startup.
3. **Network connectivity**: The Laravel app container might not be able to reach the MySQL container if they are not on the same Docker network.

### Steps to Fix:

#### Step 1: Verify `.env` File
Ensure your `.env` file has the correct database settings. It should match the database service name as defined in the `docker-compose.yml` file:

DB_CONNECTION=mysql
DB_HOST=db      # The service name must be 'db', as defined in the docker-compose.yml
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=laravel

Make sure the `DB_HOST` is exactly the name of the MySQL container service in the `docker-compose.yml` file. In this case, it’s `db`.

#### Step 2: Ensure Database Service is Running
Check if the MySQL container is up and running by listing the active containers:

docker ps

You should see a container named `mysql-db` (or whatever you named the MySQL service). If the MySQL container is not running, restart your containers:

docker-compose up -d

You can also check the logs for any issues with the MySQL container:

docker logs mysql-db

#### Step 3: Restart Containers
Sometimes, restarting the containers helps with resolving service discovery issues:

docker-compose down
docker-compose up -d

#### Step 4: Verify Network Connectivity
Ensure both the Laravel app (`laravel-app`) and MySQL (`mysql-db`) containers are part of the same Docker network, as defined in the `docker-compose.yml` file.

You can inspect the network by running:

docker network inspect laravel

Verify that both containers (Laravel app and MySQL) are listed under the same network. If the containers aren’t in the same network, it may cause communication issues between the services.

#### Step 5: Test Database Connection from Laravel Container
You can test the connection to the MySQL container from inside the Laravel container by running:

docker exec -it laravel-app bash

Once inside the container, use the following command to test the MySQL connection:

php artisan tinker
DB::connection()->getPdo();

If the connection is successful, you’ll see no errors. If there’s an error, you might need to double-check your `.env` file, the MySQL container logs, or network configuration.

### Conclusion
Make sure your `.env` file is correctly set, the containers are running, and they are connected to the same network. The `DB_HOST` should match the service name defined in `docker-compose.yml`, and restarting the containers often helps resolve networking issues between them.

User
network laravel not found
Assistant
The error `network laravel not found` suggests that the Docker network specified in your `docker-compose.yml` file does not exist yet or wasn't properly created. Docker Compose should automatically create the network when you run `docker-compose up`, but if something went wrong, you can manually handle the network.

### Steps to Resolve

#### Step 1: Check the Docker Network Configuration in `docker-compose.yml`
Ensure that your `docker-compose.yml` file has a proper network configuration. Here's how it should look:

networks:
  laravel:
    driver: bridge

This defines a network named `laravel`, and Docker Compose should automatically create it.

#### Step 2: Check Existing Docker Networks
You can list existing Docker networks to see if the `laravel` network was created or if there’s an issue:

docker network ls

This will show a list of all available Docker networks. If you don’t see `laravel`, it means the network wasn’t created.

#### Step 3: Create the Network Manually
If the network wasn't created automatically, you can manually create it:

docker network create laravel

This command will create a bridge network named `laravel`. After that, the containers should be able to communicate using this network.

#### Step 4: Restart Docker Compose
Once you verify or create the network, restart your Docker services:

docker-compose down
docker-compose up -d

This will ensure that the containers are correctly started on the `laravel` network.

#### Step 5: Verify Containers are on the Network
After restarting, verify that your containers are part of the correct network:

docker network inspect laravel

This command should show both `laravel-app` and `mysql-db` as part of the `laravel` network. If both containers are listed, they should be able to communicate with each other.

### Conclusion
Make sure your network is correctly defined in the `docker-compose.yml` file. If it’s missing or wasn’t created, manually create it with `docker network create laravel`. Once created, restart your containers and check that they are on the same network.

User
NETWORK ID NAME DRIVER SCOPE
4cbe84d7c74a bridge bridge local
91fe20704e0f host host local
ce4dbbae0970 laravel bridge local
fc9d484313cd none null local
153417907f9f shareyourthoughts_laravel bridge local
Assistant
The `laravel` network already exists, as indicated in the list of Docker networks. However, since there is another network named `shareyourthoughts_laravel`, there might be confusion between them, especially if you've used multiple networks across different projects.

### Steps to Resolve:

#### Step 1: Ensure Correct Network in `docker-compose.yml`
Check if the `docker-compose.yml` file references the correct network (`laravel`). It should look something like this:

networks:
  laravel:
    driver: bridge

Ensure that all services in the `docker-compose.yml` file (Laravel app, MySQL, Adminer) are connected to the same network (`laravel`):

services:
  app:
    networks:
      - laravel

  db:
    networks:
      - laravel

  adminer:
    networks:
      - laravel

If any of these services are connected to another network (e.g., `shareyourthoughts_laravel`), it could lead to the connection failure. Make sure they all use the `laravel` network.

#### Step 2: Check Containers Attached to the Network
After ensuring the services are connected to the correct network, run:

docker network inspect laravel

Verify that both the `laravel-app` and `mysql-db` containers are part of the `laravel` network. If they are not listed, you might need to recreate the containers.

#### Step 3: Recreate Containers
Sometimes, Docker Compose doesn't correctly apply changes to the network settings unless you fully recreate the containers. Run:

docker-compose down
docker-compose up -d --force-recreate

This will recreate all containers and ensure they are connected to the `laravel` network.

#### Step 4: Test the Setup
Once the containers are running, test the connection again by running the following inside the Laravel container:

docker exec -it laravel-app bash
php artisan tinker
DB::connection()->getPdo();

This should return no errors if the connection is successful.

### Conclusion
Make sure that all services are using the correct network (`laravel`). If necessary, remove the containers and recreate them to ensure they're attached to the correct network.

User
docker created this auto shareyourthoughts_laravel
Assistant
User's Docker environment automatically created a network named `shareyourthoughts_laravel`.
Assistant
It looks like Docker automatically created the `shareyourthoughts_laravel` network, which is likely tied to the project directory name (or a previous configuration).

### Solution:
If you prefer to use the `laravel` network instead of `shareyourthoughts_laravel`, you can make the following adjustments to ensure consistency:

#### Option 1: Use `shareyourthoughts_laravel` Network
You can modify your `docker-compose.yml` to explicitly use the `shareyourthoughts_laravel` network, which Docker already created:

1. In the `docker-compose.yml`, change the network to `shareyourthoughts_laravel`:

networks:
  shareyourthoughts_laravel:
    external: true

2. For each service (app, db, adminer), set the network:

services:
  app:
    networks:
      - shareyourthoughts_laravel

  db:
    networks:
      - shareyourthoughts_laravel

  adminer:
    networks:
      - shareyourthoughts_laravel

#### Option 2: Stick with the Custom `laravel` Network
If you'd like to stick with your manually configured `laravel` network and avoid Docker using the auto-created one, you can:

1. Make sure your `docker-compose.yml` points to the `laravel` network like this:

networks:
  laravel:
    driver: bridge

2. Remove the existing containers and restart Docker Compose to enforce this:

docker-compose down
docker network rm shareyourthoughts_laravel laravel
docker-compose up -d

This will remove the auto-created network and re-establish the containers on the correct `laravel` network.

### Conclusion:
You can either adjust your setup to use the auto-created network `shareyourthoughts_laravel` or manually configure the `laravel` network and recreate the containers to ensure the correct networking.

User
Error response from daemon: network 153417907f9f11d699b2254ceaa0a30813be35471dc9617288ed5e980a61876f not found
Assistant
The error message indicates that Docker is trying to use a network that no longer exists (perhaps it was removed or not properly initialized).

Here’s how you can resolve the issue:

### Step 1: Check Available Networks
First, verify which networks are available by running:

docker network ls

You’ll get a list of existing networks. Make sure the `shareyourthoughts_laravel` or `laravel` network (whichever you intend to use) is in the list.

### Step 2: Remove Stale Networks (If Any)
If you see networks that are no longer in use or causing problems, you can remove them using:

docker network rm NETWORK_ID

Replace `NETWORK_ID` with the network's actual ID (e.g., `153417907f9f`). For example:

docker network rm 153417907f9f11d699b2254ceaa0a30813be35471dc9617288ed5e980a61876f

### Step 3: Recreate the Missing Network
If the necessary network is missing (for example, `laravel`), recreate it manually:

docker network create laravel

If you are using the `shareyourthoughts_laravel` network instead, you don't need to manually create it because Docker Compose should automatically recreate it.

### Step 4: Restart the Containers
Once the correct network is in place, bring your containers back up:

docker-compose down
docker-compose up -d

This will restart the containers and ensure they are attached to the correct network.

### Step 5: Inspect the Network
You can inspect the network to ensure the services (e.g., `laravel-app`, `mysql-db`, etc.) are connected:

docker network inspect laravel

If using `shareyourthoughts_laravel`, replace `laravel` with `shareyourthoughts_laravel` in the command above.

### Conclusion
By removing stale networks, manually recreating any missing ones, and restarting your containers, you should be able to resolve the "network not found" issue. This will ensure your containers are correctly attached to the proper Docker network.

Leave a Comment

Your email address will not be published. Required fields are marked *