How To Run Containers In Docker?
To understand the role of shea l in a container, we are going to consider a simple example. We will create a file name user_env.txt which stores the value “Anshul” signifying the user. We will write a Python script with / endpoint which returns the value stored in the file user_env.txt. We will then create a dockerFile for creating image of the python script. Then we will start a container using that image.
After the container is up and running we will get into the containers shell using its id and change the value of user_env.txt file inside the containers file system. Which will also be reflected at the / endpoint.
Create a Directory gfg and open that directory in code editor of you choice
1. Creating python script : Create a file named app.py and copy paste the below code.
Python
from flask import Flask app = Flask(__name__) @app .route( "/" ) def hello_world(): with open ( '/user_env.txt' ) as file : user_value = file .readline().strip() return f 'USER environment variable value: {user_value}' if __name__ = = "__main__" : app.run(host = "0.0.0.0" , port = 5000 ) |
The above script open the file user_env.txt, read its text and send it back as response to the / endpoint.
2. Creating Dockerfile : Create a file named Dockerfile in the gfg directory and copy paste the below code in it
FROM python:3.8
RUN pip install flask
COPY . /
CMD [“python”, “app.py”]
3. user_env.txt file : Create a file named user_env.txt inside the gfg directory and write some text in it.
4. Building Image : Now to create a container we first need to build an image using the dockerfile we created above. To do so run the below command in the terminal. Ensure you are in the gfg path.
docker build -t docker_image .
Above command will create an image name docker_image
5. Start Container : To start the container using the docker_image image run the below command in the terminal
docker run -it -p 8000:5000 docker_image
Above command will start the container, you can check that the container is running or not using docker desktop.
The gfg directory should contains the below files :
Open the web browser and enter the below command :
http://localhost:8000
Above URL should display the contents of the user_env.txt file.
6. Container Id: You can check whether the container is running or not and also the id associated with the container using the below command
docker ps
It will display all the container currently running on the machine along with other info such as id status etc.
Docker – Containers & Shells
Docker is a set of platforms as a service (PaaS) products that use Operating system-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries, and configuration files; they can communicate with each other through well-defined channels. All containers are run by a single operating system kernel and therefore use fewer resources than a virtual machine.