使用docker部署redis与python,并实现容器联通

目标是使用docker分别部署python与redis,并联通

  1. 安装docker

  1. 创建网络
$ docker network create -d bridge net-test
  1. 创建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"
  1. 创建python容器
$ docker run -itd --name=python --network=net-test python:3.6.0
$ docker exec -it python /bin/bash

我比较喜欢python3.6.0版本所以用它

  1. 检查网络是否相通
# 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
  1. 安装python-redis
pip install redis
  1. 使用测试脚本
# vim test.py

注意这里的host使用第5步获取的ip,不要使用127.0.0.1localhost

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!'
  1. 返回redis容器,检查结果
127.0.0.1:6379> get test
'hello world!'

docker部署很方便,唯一麻烦的是,两个容器联通同一个网络后,需要使用局域网ip找到对方

posted @ 2020-12-29 11:41  trty  阅读(707)  评论(0)    收藏  举报