Home > Back-end >  How to install a Python package inside a docker image?
How to install a Python package inside a docker image?

Time:01-23

Is there a way to install a python package without rebuilding the docker image? I have tried in this way:

docker compose run --rm web sh -c "pip install requests"

but if I list the packages using

docker-compose run --rm web sh -c "pip freeze"

I don't get the new one. It looks like that is installed in the container but not in the image.

My question is what is the best way to install a new python package after building the docker image? Thanks in advance

CodePudding user response:

docker-compose is used to run multi-container applications with Docker.

It seems that in your case you use Docker image with python installed as entrypoint to do some further work.

After building docker image you can run it:

$ docker run -dit -name my_container_name image_name

And then run:

$ docker exec -ti my_container_name bash or

$ docker exec -ti my_container_name sh

in case there is no bash in the docker image. This will give you shell access to the container you just created. Then if there is pip installed inside your container you can install whatever python package you need like you would do on your OS.

Take note that everything you install is only persisted inside the container you created. If you delete this container, all the things you installed manually will be gone.

CodePudding user response:

I don't know too much about docker but if you execute your commands, the docker engine will spin up a new container based on your web image and runs the pip install requests command. After it executed the command, the container has nothing more to do and will stop. Since you specified the --rm flag, the docker engine will remove your new container after it has stopped such that the whole container and thus also the installed packages are removed.

AFAIK you cannot add packages without rebuilding the image. I know that you can run the command without removing the container and that you can also make images from your containers. (Those images should include the packages then).

CodePudding user response:

Check the docs here for a simple Python example.

  • Related