run bash command outside docker container

Viewed 51

I built API using FastAPI that calls some bash commands. Now I want to make a docker container for my app but I encountered the following issue: if I create a docker container, the app won't run bash commands. I guess I need to get out of docker container to run bash commands but I am not sure that it is possible. Any suggestions? Apologies in advance if my question is confusing. Here is my Docker File

FROM python:3.9

WORKDIR /code

COPY ./requirements.txt /code/requirements.txt

RUN pip3 install --no-cache-dir --upgrade -r /code/requirements.txt

COPY ./app /code/app

# CMD ["python", "./app/main.py"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

and here is an example of how I run bash command (it is actually a docker command)

@app.post("/stop-camera")
async def stop_camera(info: Request):
    req_info =  await info.json()
    file_name = str(req_info["id"])
    result1 = subprocess.run([str(env_dictionary["STOP"])+ file_name], shell = True)
    result2 = subprocess.run([str(env_dictionary["REMOVE"])+ file_name], shell = True)

    return {
        "status" : "SUCCESS",
        "stop" : result1,
        "rm" : result2
    }
 
1 Answers

Here's a very simple example of UDP communication between something running on a docker host and something running inside a container.


On the host, start a simple docker container passing it a way to get the host's IP address:

docker run -it --add-host host.docker.internal:host-gateway alpine:latest ash

Then, still outside the container and on the host, wait for a command on UDP port 65000 from the container. Note I am using netcat here, but you would likely use Python since you have that already:

# Listen on UDP port 65000
nc -u -l 65000

Obviously you could run this in a loop to wait for multiple commands, and you could parse different commands that arrive and react differently to different commands and you could also check the source of the commands, or encrypt them for some level of security...


Inside the container, I quickly add netcat but you would probably use Python again:

# Install netcat
apk update && apk install netcat-openbsd

# Send command to host via UDP on port 65000
echo STOP | nc -u host.docker.internal 65000
Related