0

I have two services. Redis and PHP. How to make php wait for the launch of redis and write about it.I tried using healthcheck-s but apparently I am not setting it up correctly.

docker-compose.yml

version: '2'
services:
  php:
    build:
      context: docker/web
      dockerfile: Dockerfile-php-7.0
    container_name: php
    ports:
      - "8280:80"
    links:
      - redis:redis
  redis:
     build: docker/cache
     container_name: redis

Dockerfile-php-7.0

FROM php:7.0
RUN pecl install redis \
&& docker-php-ext-enable redis
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
CMD [ "php", "./index.php"]
EXPOSE 80


 index.php    
                                                                                  
<?php
echo 'Starting';
$redis = new Redis();
$redis->connect(getenv('host'), getenv('6379'));
var_dump($redis->incr('foo'));
?>

Dockerfile

FROM redis:3.2-alpine
COPY conf/redis.conf /usr/local/etc/redis/redis.conf
CMD [ "redis-server", "/usr/local/etc/redis/redis.conf" ]
EXPOSE 6379

Don't be afraid to scold me. I am just starting to learn docker. I would be very grateful for any help !!!

Rony
  • 163
  • 1
  • 5
  • you can probably use depends_on for php service in docker-compse.yml. https://docs.docker.com/compose/compose-file/compose-file-v2/#depends_on – Rony Sep 23 '21 at 11:10

1 Answers1

0

Here is the docker-compose.yml file that you can use:

version: '2.1'
services:
  php:
    build:
      context: docker/web
      dockerfile: Dockerfile-php-7.0
    container_name: php
    ports:
      - "8280:80"
    depends_on:
      redis:
        condition: service_healthy
  redis:
    build: docker/cache
    container_name: redis
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s

I also change the PHP script (index.php) as follows:

<?php
echo 'Starting';
$redis = new Redis();
$redis->connect('redis', '6379');
var_dump($redis->incr('foo'));

Now the whole stack works in my machine. I can connect redis container from php.

The php container log shows the following

docker logs -f php
Startingint(1)
Rony
  • 163
  • 1
  • 5
  • Yes! Thanks a lot . It works. But I need the php application to wait before starting redis through the healtcheck mechanism. Do you have any idea how to do this? – lehan1819mailru Sep 23 '21 at 13:57
  • Hi @lehan1819mailru, I've changed the docker-compose.yml file in my answer. Please note that I changed the "version" in docker-compose.yml to 2.1 – Rony Sep 23 '21 at 17:39