Docker-compose Networks and Volumes
Using docker-compose yaml file, we can create multiple networks and volume in an application.
The below code shows how to create networks using YAML file
version: '3'
services:
web:
build:
context: .
dockerfile: Dockerfile
args:
- PYTHON_VERSION=3.4-alpine
image: coolgourav147/python-redis
ports:
- "5000:5000"
networks:
- appnetwork
redis:
image: "redis:alpine"
volumes:
- myredisdata:/data
networks:
- appnetwork
redis2:
image: "redis:alpine"
volumes:
- myredisdata2:/data
networks:
- appnetwork2
networks:
appnetwork:
appnetwork2:
volumes:
myredisdata:
myredisdata2:
We have defined 3 containers inside services, each container is using network and volume. At the end network is the property/field which will create 2 networks appnetwork and appnetwork2,likewise, volumes are the property to create volume inside the container.Users can attach the network with any container if and only if it has been created in YAML file.
Before running the docker-compose up -d command ,there are no networks and new volumes created.
gaurav@learning-ocean:~/python_redis$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
gaurav@learning-ocean:~/python_redis$ docker volume ls
DRIVER VOLUME NAME
gaurav@learning-ocean:~/python_redis$ docker network ls
NETWORK ID NAME DRIVER SCOPE
0022a9f511fe bridge bridge local
3a33f83c3663 host host local
e4ebd601732c none null local
let run docker-compose up
[email protected]:~$ docker-compose up -d
Creating network "docker-volumes_appnetwork" with the default driver
Creating network "docker-volumes_default" with the default driver
Building web
Sending build context to Docker daemon 5.632kB
let check network, volume and containers again
[email protected]:~$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d0df46f4f293 redis:alpine "docker-entrypoint.s…" 9 seconds ago Up 7 seconds 6379/tcp docker-networks_redis_1
11f7d05376d2 coolgourav147/python-redis "python app.py" 9 seconds ago Up 6 seconds 0.0.0.0:5000->5000/tcp docker-networks_web_1
5f9d87371ad6 redis:alpine "docker-entrypoint.s…" 9 seconds ago Up 6 seconds 6379/tcp docker-networks_redis2_1
[email protected]:$ docker volume ls
DRIVER VOLUME NAME
local docker-networks_myredisdata
local docker-networks_myredisdata2
[email protected]:~$ docker network ls
NETWORK ID NAME DRIVER SCOPE
0022a9f511fe bridge bridge local
4dd17646884a docker-networks_appnetwork bridge local
d124edf4aa4c docker-networks_appnetwork2 bridge local
3a33f83c3663 host host local
e4ebd601732c none null local
[email protected]:~$