How to Call a Service Running in a Docker Container from Another Docker Container on the Same Machine?

I have several Docker containers running on the same machine. One of them performs periodic tasks (cronjob) that need to access a Redis service running in a separate container. The cronjob should run every hour and use Redis to interact with other worker containers.

My current docker-compose.yml file launches the Redis service and worker containers. I don't want to expose the Redis port to localhost. Is it possible to add a cronjob to the same docker-compose.yml to use the internal Docker network? If not, how can I ensure communication between the cronjob container and Redis without opening the port?

docker-compose.yml:

		
version: '3.8'

services: redis_service: image: "redis:alpine" container_name: rediscontainer expose: - "6380"

worker_instances: image: custom/worker-app container_name: workerapp depends_on: - redis_service deploy: replicas: 5

Answers

  • Gravatar — онлайн-сервис, позволяющий пользователям Интернета поддерживать постоянную картинку на большинстве сайтов.

    Julien Bernard

    Thank you for the detailed answer.

    Your solution helped me.

    0
  • Gravatar — онлайн-сервис, позволяющий пользователям Интернета поддерживать постоянную картинку на большинстве сайтов.

    Julien Bernard

    Thank you!

    0
  • Gravatar — онлайн-сервис, позволяющий пользователям Интернета поддерживать постоянную картинку на большинстве сайтов.

    Karl Wagner

    You can set up communication between your containers without exposing the Redis port to localhost by using Docker's internal network. To do this, add a cronjob container to the same docker-compose.yml and use the Redis service name for the connection.

    Example docker-compose.yml with cronjob:

    		
    version: '3.8'

    services: redis_service: image: "redis:alpine" container_name: rediscontainer expose: - "6380"

    worker_instances: image: custom/worker-app container_name: workerapp depends_on: - redis_service deploy: replicas: 5

    scheduled_task: image: custom/cronjob-app container_name: cronjobapp environment: - REDIS_URL=http://rediscontainer:6380 entrypoint: ["./run_task.sh"] restart: "no" networks: - default

    networks: default: driver: bridge

    In this example:
    scheduled_task — new service for the cronjob.
    REDIS_URL — environment variable pointing to the Redis service within the Docker network.
    entrypoint — command to run the task script.
    Containers are on the same Docker network (default), allowing them to communicate via service names.

    0
  • Gravatar — онлайн-сервис, позволяющий пользователям Интернета поддерживать постоянную картинку на большинстве сайтов.

    Simone Bruno

    Add a cronjob container to the same docker-compose.yml and use the Redis service name for internal connection, avoiding exposing ports externally.

    0