ChatGPT解决这个技术问题 Extra ChatGPT

Docker: How to use bash with an Alpine based docker image?

I created a docker image from openjdk:8-jdk-alpine but when I try to execute simple commands I get the following errors:

RUN bash
/bin/sh: bash: not found

RUN ./gradlew build
env: can't execute 'bash': No such file or directory
For googlers: docker run --rm -i -t alpine /bin/sh
Start container ( interactively): docker exec -it container_id /bin/sh

m
miftahulrespati

Alpine docker image doesn't have bash installed by default. You will need to add the following commands to get bash:

RUN apk update && apk add bash

If you're using Alpine 3.3+ then you can just do:

RUN apk add --no-cache bash

To keep the docker image size small. (Thanks to comment from @sprkysnrky)


The apk upgrade is not required.
I prefer use the recomendation of @Yuva using RUN /bin/sh instead of RUN bin/bash
That is entirely up to you, many people need bash specific feature.
why should I use the --no-cache option?
Y
Yuva

Try using RUN /bin/sh instead of bash.


OP asked for bash. sh is not bash.
But this is very useful comment anyway - most people will be fine with sh - and it does not require additional 50mb of image size
Easy and straightforward. Most times we only need to run shitty commands (ls, ps, whatever), sh covers those scenarios. thanks!
@kboom the bash package adds about 4MB to the size of alpine:3.8, roughly doubling it, but still far from 50MB.
This should be a comment rather than an answer. At the same time I agree that the accepted answer should include a comment that if possible one should stick to sh rather than install bash as it increases the size of the image.
u
user1738546
RUN /bin/sh -c "apk add --no-cache bash"

worked for me.


The initial part of the RUN command is unnecessary. You can just write RUN apk add --no-cache bash directly
S
Sahith Vibudhi

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.

Reference: https://github.com/smebberson/docker-alpine/issues/43


O
Onat Korucu

If you have the option (for instance if you are just creating the script), using an alpine image with bash installed such as alpine-bash might be clever.


J
James Geddes

The official bash image is based on Alpine and prevents you from needing to install bash every time. Simply use

docker pull bash

This was first published on Oct 19, 2016 at 6:43 pm.