Linux’s Screen lets you run terminal applications to a Server in the background even if you disconnect from the ssh connection. It’s especially useful for us when running APIs or Web Apps like Streamlit.
The problem with Screen is that if the server goes down for any reason like update, restart, etc. you have to run all the screen sessions manually one by one. A great solution for it is to create an executable file and add all the screen sessions there.
Firstly we need to create a “sh” file having in its first line the following.
Then, we need to add the screen session commands.
The screen command has to do the following:
- Start a Screen Session
- Activate the App/API Environment(if any)
- Navigate to App/API’s path
- Run the App/API
- Detach the Screen Session
To achieve all these 5 steps, we can run the following:
screen -dmS app_name bash -c 'cd /path_to_app; conda activate app_env; /path_to_app/app.py'
Let’s break down this line of code.
–dmS: Opens a Screen Session and then detaches it.
bash -c: Runs a bash script. We separate every bash command with a ‘;’.
In the script, we first navigate to the app/api’s directory, and then using the app/api’s environment, we run the file.
Tip: In order to find the full path of the Python or Streamlit of the app/api’s environment, you can run the following when it’s activated:
Putting It All Together
Now, Let’s add some screen session examples in our .sh file. Let’s call it screens.sh.
#!/bin/sh screen -dmS python_api bash -c 'cd /python_api; /home/conda/envs/custom_env/bin/python /python_api/app.py' screen -dmS streamlit_app bash -c 'cd /streamlit_app; ~/.conda/envs/custom_env/bin/streamlit run /streamlit_app/app.py'
Finally, you can run the screens.sh, running the following:
Now you should have all your screen sessions running and detached.
As a bonus, you can kill all the screen sessions at once using the following command: