import time
from modbus_tk import modbus_tcp
import modbus_tk.defines as mdf
import redis
defrun_server():
r_c =None
server = modbus_tcp.TcpServer(address='0.0.0.0')
slave = server.add_slave(1)
slave.add_block('ns', mdf.HOLDING_REGISTERS,0,500)
server.start()whileTrue:try:
slave.set_values('ns',0,list(map(int, r_c.mget(r_c.keys()))))except Exception:
r_c =None
r_c = redis.Redis('xx.xx.xx.xx', db=1)
time.sleep(5)if __name__ =='__main__':
run_server()
2 dockerfile 文件
FROM python:3.9
MAINTAINER Fei
WORKDIR /server
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
COPY ..
CMD ["python","modbus_server.py"]
3 制作镜像
docker build -t modbusserver:tag #tag为标签号
4 启动一个容器
docker run --name md01 -p 9002:502 -d modbusserver:0.3
5 查看镜像内
[root@ZJF-SERVER mdserver]# docker exec -it md01 /bin/bash
root@25449cac3174:/server# ls
Dockerfile modbus_server.py requirements.txt
root@25449cac3174:/server# pwd
/server
root@25449cac3174:/server# cd /
root@25449cac3174:/# ls
bin boot dev etc home lib lib64 media mnt opt proc root run sbin server srv sys tmp usr var
root@25449cac3174:/# python
Python 3.9.7 (default, Oct 132021, 09:00:49)[GCC 10.2.1 20210110] on linux
Use exit() or Ctrl-D (i.e. EOF) to exit>>> exit()