HHH
HHH

Reputation: 6485

How to create docker volume in docker compose

I have a docker-compose file to start my services. I need to have a volume for my services on the host machine. From what I understood, I have to create the volume first on my host machine (using docker volume create ) and them put the volume name in my docker-compose file. I want to know whether this is the only option to create a volume? Or I can somehow create the volume on the host machine automatically in my docker-compose file?

Upvotes: 2

Views: 593

Answers (1)

Jakub Bujny
Jakub Bujny

Reputation: 4628

You can create named volume directly in docker-compose e.g.

version: '2.4'

services:
  ubuntu:
    image: ubuntu:18.04
    volumes:
      - myvolume:/opt/myvolume

volumes:
  myvolume: {}

Edit:

Volume doesn't need to exist on host machine, see example log:

➜ /tmp docker-compose up                                                            
Creating volume "tmp_myvolume" with default driver                                  
Creating tmp_ubuntu_1 ... done

Edit 2:

Answering to comment: volumes is section where you can define configuration for some volumes. In my example I passed empty configuration but it can looks like e.g.

volumes:
   myvolume:
     name: othermyvolumename
     driver: nfs-driver

After defining volumes you can refer them in services section.

Upvotes: 2

Related Questions