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
Karl Wagner
7 months ago
1 comment
Rating
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:
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.
Julien Bernard
7 months ago
Rating
Thank you for the detailed answer.
Your solution helped me.
Simone Bruno
7 months ago
1 comment
Rating
Add a cronjob container to the same docker-compose.yml and use the Redis service name for internal connection, avoiding exposing ports externally.
Julien Bernard
7 months ago
Rating
Thank you!