How to setup python environment to run code in docker

Arjun Chauhan
3 min readNov 3, 2020

--

Docker is container technology which became popular as soon as it was launched in 2013. Docker are usually used to run a single service at a time. Docker creates an isolated environment on the system although it uses the resources of it’s host but works in isolation. This makes docker very useful in various ways.

Firstly the docker containers are extremely lightweight and an OS can be installed within a second. This saves a lot of time of users trying to test some new product or any other use cases they might be working on

Today I would creating a python environment in docker. I would be using the centos image which we can pull from docker.hub or using the below command

docker pull centos

The setup is pretty straightforward so let’s just right get into it.

1. Start docker services

Before we create a container on docker we need to first start the services

systemctl start docker

2. Create a new container

To create a new container we can use the following command

docker run -it centos

the -it is used in the above command because we want an interactive terminal to be used in the docker terminal.

If you want to use a previously created container you can first list the existing docker containers using

docker ps -a

Then you can get the id of any one container to launch it.

So when we want to use an existing container we first start it and then go inside that container. However when we run a container for the very first time using the “run” command that I mentioned earlier we are directly landed into the container.

docker start “container_id”

docker attach “container_id”

3. Python Environment

After this command we are landed inside the container. So a docker container is like an isolated terminal which can be used like a normal OS terminal in most cases. The yum package manager is already configured so we can directly use it

yum install python3

This installs python in the enviornment. To start using python we just need to type python3 in the terminal which activates the python interpreter in the CLI itself.

or we can use the following command to use the python in vim code editor

vim file_name.py

This helps in creating projects and not just debugging the code. But the main catch here is that we used the docker to install the interpreter. The major benifit of using this environment will be that if due to certain bad program if the system is corrupted, we can just shutdown the system and create a new container without harming the host system.

--

--