context or workdir for docker-compose

I'm learning docker

I need to specify the working directory for a docker image, I think that'll be something like this:

version: '2'
services:
  test:
    build:
      context: ./dir

Now I want to make the image python:onbuild to run on the ./dir, but I dont want to create any Dockerfile inside the ./dir.

The docker-compose manual says nothing about that.

Is it possible? How to do that?


Solution 1:

I think you're looking for working_dir. Search for "working_dir" in the docker-compose reference.

Solution 2:

You can specify the working directory as follows.

version: '2'
services:
  test:
    build:
      context: ./dir
    working_dir: /dir

Solution 3:

Possibly not exactly what you were looking for, but you can specify the "context" for the docker build to be a different directory to where the actual Dockerfile lives.

build:
  context: ./folder/containing/files
  dockerfile: path/to/dockerfile/relative/to/context/Dockerfile

Any ADD/COPY commands in your Dockerfile then act as if they are relative to the context regardless of where the Dockerfile actually is.

Solution 4:

The build configuration in Docker Compose just ends up in a call to docker build, so you need to have a Dockerfile to use that workflow.

As the docs for python:onbuild say, you can start with a minimal Dockerfile that just contains FROM python:onbuild. But as they also say, :onbuild isn't a great option, you'll have much more control building your own Dockerfile FROM python.