使用docker部署redis与python,并实现容器联通
目标是使用docker分别部署python与redis,并联通
- 安装docker
略
- 创建网络
$ docker network create -d bridge net-test
- 创建
redis容器
$ docker run -itd --name=redis --network=net-test redis
$ docker exec -it redis /bin/bash
进入容器检查
redis是否开启
# redis-server
# redis-cli
设置密码
127.0.0.1:6379> config set requirepass password
OK
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "password"
- 创建
python容器
$ docker run -itd --name=python --network=net-test python:3.6.0
$ docker exec -it python /bin/bash
我比较喜欢
python3.6.0版本所以用它
- 检查网络是否相通
# ping redis
PING redis (172.18.0.3): 56 data bytes
64 bytes from 172.18.0.3: icmp_seq=0 ttl=64 time=0.202 ms
64 bytes from 172.18.0.3: icmp_seq=1 ttl=64 time=0.129 ms
64 bytes from 172.18.0.3: icmp_seq=2 ttl=64 time=0.112 ms
64 bytes from 172.18.0.3: icmp_seq=3 ttl=64 time=0.114 ms
- 安装
python-redis库
pip install redis
- 使用测试脚本
# vim test.py
注意这里的
host使用第5步获取的ip,不要使用127.0.0.1或localhost
test.py
#coding:utf8
import redis
r = redis.Redis(host='172.18.0.3', port=6379,password="password")
r.set('test', 'hello world!')
print(r.get('test'))
保存后添加执行权限
# chmod +x test.py
执行脚本
# python test.py
b'hello world!'
- 返回
redis容器,检查结果
127.0.0.1:6379> get test
'hello world!'
docker部署很方便,唯一麻烦的是,两个容器联通同一个网络后,需要使用局域网ip找到对方

浙公网安备 33010602011771号