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
Julien Bernard
Thank you for the detailed answer.
Your solution helped me.
Julien Bernard
Thank you!
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:
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.
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.