Connect Redis from Another Container
1. Issue
I started a redis container in my local environment and now I want to connect and/or send data to it from another container.
1.1. Reproduce
1.1.1. docker cli
Let’s assume that I started a redis container from cli
:
$ docker run \
--name redislocal \
-p "6379:6379" \
redis:6.2.5
Or in a more appropriate way:
$ docker run \
--name redislocal \
--hostname redislocal \
-p "127.0.0.1:6379:6379" \
-d \
redis:6.2.5 \
redis-server \
--appendonly yes \
--requirepass "paSSw0rD"
1.1.2. docker-compose
Maybe I started it via docker-compose
:
$ docker-compose -f compose-redis-local.yml up -d --build
And compose-redis-local.yml
something like:
# compose-redis-local.yml
version: "3.5"
volumes:
local_redis_data: {}
services:
redis:
container_name: redislocal
hostname: redislocal
image: redis:6.2.5
command: redis-server --appendonly yes --requirepass "paSSw0rD"
ports:
- "127.0.0.1:6379:6379"
volumes:
- local_redis_data:/data
restart:
unless-stopped
2. Solution
Sorry: there is NO way you can connect to above redis containers from another container.
When you spawn containers from docker-compose
—docker-compose example, docker will:
- Create a network
mayapp_default
withbridge
driver (myapp
is the directory you’re in) - Create
redislocal
container and add it tomayapp_default
network under the nameredis
Similar applies to docker cli
.
2.1. Custom Network
What you need is a user defined custom shared network: You should create a custom network than respawn your containers in this network.
Create a network called local-dev:
$ docker network create local-dev
Ensure it was created:
|
|
2.1.1. docker cli
Start within this network:
|
|
2.1.2. docker-compose
Use this network as an external network in your compose file:
|
|
In addition to those, instead of User-defined bridge networks you can use host networks however I don’t like this approach since it breaks the isolation nature of docker.
For more info you can look at this official docker docs:
3. Connect
Now you can connect in the same network:
$ docker run \
-it \
--rm \
--net local-dev \
redis:6.2.5 \
redis-cli \
-h redislocal \
-a "paSSw0rD" \
ping
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
PONG
All done!