4

I understand that each RUN command creates a layer. Suppose I have the following RUN commands:

RUN python -m pip install --upgrade pip
RUN python -m pip install --upgrade setuptools
RUN pip install -r requirements.txt 

I wish to run all the command in one run command. Is the below OK to use?

RUN python -m pip install --upgrade pip; python -m pip install --upgrade setuptools; pip install -r requirements.txt 

If I use the following, then it gives me an error "The token '&&' is not a valid statement separator in this version.":

RUN python -m pip install --upgrade pip && python -m pip install --upgrade setuptools && pip install -r requirements.txt
variable
  • 8,262
  • 9
  • 95
  • 215

3 Answers3

9

Yes you can and its a good practice

Instead of doing this

RUN python -m pip install --upgrade pip
RUN python -m pip install --upgrade setuptools
RUN pip install -r requirements.txt 

Try this

RUN python -m pip install --upgrade pip &&\
    python -m pip install --upgrade setuptools &&\
    pip install -r requirements.txt 

Advantages with that approach

Each instruction in the Dockerfile adds an extra layer to the docker image The number of instructions and layers should be kept to a minimum as it ultimately affects the build performance and time

UDIT JOSHI
  • 1,298
  • 12
  • 26
  • 1
    It gives an error: The token '&&' is not a valid statement separator in this version. – variable Jun 01 '20 at 07:16
  • Is there a way to have comments for each line with this approach? – ReenigneArcher Oct 07 '22 at 14:29
  • 1
    About build performance: If you have multiple layers, and you only change the top layer, then the lower layers won't be rebuilt. So subsequent rebuilds can actually be faster if you have multiple layers, if the lower layers are cached. – donquixote Feb 25 '23 at 04:36
1

Yes it is ok to combine RUN commands and it will reduce the number of layers in the docker image too!

RUN python -m pip install --upgrade pip && python -m pip install --upgrade setuptools && pip install -r requirements.txt

Should do!

UPDATE: Please try this command.

RUN python -m pip install --upgrade pip && python -m pip install --upgrade setuptools && pip install -r requirements.txt 
Anuradha Fernando
  • 1,063
  • 12
  • 17
0

It is encouraged to combine multiple RUN statements, as it reduces the number of layers created

See: https://github.com/mysql/mysql-docker/blob/mysql-server/5.7/Dockerfile

Palash Goel
  • 624
  • 6
  • 17