简体   繁体   中英

docker-compose vs creating and running an image

I'm new to docker and trying to understand what's best for my project (a webapp).

So far, I understand that I can either :

  • use docker-compose up -d to start a container defined by a set of rule in a docker-compose.yaml
  • build an image from a dockerfile and then create a container from this image

If I understand correctly, docker-compose up -d allows me (via volumes ) to mount files (eg my application) into the container. If i build an image however, I am able to embed my application natively in it (with a Dockerfile and COPY instruction).

Is my understanding correct ? How should I choose between those 2 choices ?

Docker Compose is simply a convenience wrapper around the docker command.

Everything you can do in docker compose, you can do plainly with running docker.

For example, these docker commands:

$ docker build -t temp .
$ docker run -i -p 3000:80 -v $PWD/public:/docroot/ temp

are similar to having this docker compose file:

version: '3'

services:
  web:
    build: .
    image: temp
    ports: ["3000:80"]
    volumes:
    - ./public:/docroot

and running:

$ docker-compose up web

Although docker compose advantages are most obvious when using multiple containers, it can also be used to start a single container.

My advice to you is: Start without docker compose, to understand how to build a simple image, and how to run it using the docker command line. When you feel comfortable with it, take a look at docker compose.

As for the best practice in regards to copying files to the container, or mounting them - the answer is both , and here is why:

When you are in development mode, you do not want to build the image on every code change. This is where the volume mount comes into play. However, your final docker image should contain your code so it can be deployed anywhere else. After all, this is why we use containers right? This is where the COPY comes into play.

Finally, remember that when you mount a volume to the container, it will "shadow" the contents of that folder in the container - this is how using both mount and COPY actually works as you expect it to work.

Docker-compose is just a container orchestrator. I just provides you a simple way to create multiple related containers. The relationship between containers can be volumes, networks, start order, environment variables, etc.

In background, docker-compose uses plain docker. So, anything you can do using docker-compose (mounting volumes, using custom networks, scaling) can be done using docker commands (but of course is harder).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM