Home > OS >  Cant connect apache mysql when using docker swarm
Cant connect apache mysql when using docker swarm

Time:10-22

New to using docker.
I am trying to use docker swarm to deploy my webapp on multiple nodes on GCP. I tested my docker-compose.yml using docker-compose up -d and it works perfectly. I am able to connect with and access mysql database.

But then I tried deploying using docker swarm from manager using sudo docker stack deploy -c docker-compose.yaml social_network, I get an error on the database connection.

I figured the issue is with using the image: php:8.1-apache in docker-compose.yml, but using image is necessary for docker swarm. Is there any workaround for this?

docker-compose.yml

version: '3.3'
services:
  web:
    image: php:8.1-apache
    build:
      context: ./php
      dockerfile: Dockerfile
    container_name: php81
    depends_on:
      - db
    volumes:
       - ./src/social_network:/var/www/html/
    ports:
       - 8080:80
    deploy:
       replicas: 3

  db:
    container_name: mysql8
    image: mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root

    ports:
       - 6033:3306
    deploy:
       replicas: 3

  phpMyAdmin:
      image: phpmyadmin
      container_name: myphpMyAdmin

      environment:
        PMA_ARBITRARY: 1
      
      restart: always

      ports:
        - 8082:80

      deploy:
       mode: replicated
       replicas: 3

Dockerfile

FROM php:8.1-apache
RUN apt-get update && apt-get upgrade -y
RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli
EXPOSE 80

Error

<br /> <b>Fatal error</b>: Uncaught Error: Call to undefined function mysqli_connect() in /var/www/html/php/config.php:3 Stack trace: #0 /var/www/html/php/login.php(3): include_once() #1 {main} thrown in <b>/var/www/html/php/config.php</b> on line <b>3</b><br />

In the config.php file

$conn = mysqli_connect("db","root","root","social_network");

CodePudding user response:

Docker swarm does not support build:, so your stack deploy will be using the base php:8.1-apache image you have instructed in the compose.

You will need to build your own version of the image and publish it to a registry - docker hub has a free tier, GCP will have some kind of GCR, or you can just deploy a registry:2 instance to your swarm to self host your own images.

change the docker-compose.yml image references to target this repository and then your build process can be something like:

docker compose build
docker compose push
docker stack deploy ...
  • Related