Working with Container Networking
- Lets do some changes in application files,
- Create python app file
vim app.py
from flask import Flask from flask_redis import FlaskRedis app = Flask(__name__) app.config['REDIS_URL'] = 'redis://redis:6379/0' redis = FlaskRedis(app) @app.route('/') def counter(): return str(redis.incr('web2_counter'))
save the file
ESC + wq!
- Create python app dependency definition file
vim requirements.txt
Flask==0.12 flask-redis==0.3
save the file
ESC + wq!
- Create python app file
- Build a new docker image with tag as web2
docker image build -t web2 .
- Pull Redis based of alpine from docker hub
docker image pull redis:3.2-alpine
- List of docker network
docker network ls
- Inspect a network
docker network inspect bridge
- Run a redis container
docker run --rm -itd -p 6379:6379 --name redis redis:3.2-alpine
-rm = removes container when it stopped -it = interactive mode -d = Run container is background --name = Define container name
- Run a flask container
docker container run --rm -itd -p 5000:5000 -e FLASK_APP=app.py -e FLASK_DEBUG=1 --name web2 -v $PWD:/app web2
-e =execute command in Docker -p = Define container & host port -it = interactive mode -rm = removes container when it stopped --name = Define container name -d = Run container is background -v = Define volume
- Check IP address of redis container
docker exec redis ifconfig
- Check IP address of web2 container
docker exec web2 ifconfig
- Ping redis conatiner from web2 using redis container’s IP address
docker exec web2 ping 172.17.0.3
- Check redis container hosts file
docker exec redis cat /etc/hosts
- Creating a custom bridge network
docker network create --driver bridge firstnetwork
- Inspect newly created network
docker network inspect firstnetwork
- Stop redis & web2 containers
docker container stop web2
docker container stop redis
- Run redis & web2 container in newly created network
docker container run --rm -itd -p 6379:6379 --name redis --net firstnetwork redis:3.2-alpine
docker container run --rm -itd -p 5000:5000 -e FLASK_APP=app.py -e FLASK_DEBUG=1 --name web2 --net firstnetwork -v $PWD:/app web2
-e =execute command in Docker -p = Define container & host port -it = interactive mode -rm = removes container when it stopped --name = Define container name -d = Run container is background -v = Define volume -net = Define network
- Ping redis container from web2 using docker name, this is only possible in custom network not in default network
docker exec web2 ping redis
- Lets run some redis-cli commands to check counter in action
docker exec -it redis redis-cli
KEYS *
INCRBY web2_counter 1000000
- Stop web2 & redis containers
docker container stop web2
docker container stop redis