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

Julien Bernard

7 months ago

4 answers

77 views

Rating

07
Answer

Answers

Karl Wagner

7 months ago

1 comment

Rating

00

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.

Reply

    Julien Bernard

    7 months ago

    Rating

    00

    Thank you for the detailed answer.

    Your solution helped me.

    Reply

Simone Bruno

7 months ago

1 comment

Rating

00

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

Reply

    Julien Bernard

    7 months ago

    Rating

    00

    Thank you!

    Reply