我正在寻找用于发送请求和执行方案的小型休息服务器。
我在这里找到它:
Create a minimum REST Web Server with netcat nc
我正在尝试执行此小型Rest服务器。
在Dockerfile和bash脚本下方。
Docker文件
FROM debian
ADD ./rest.sh /rest.sh
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive \
&& apt-get install -y net-tools netcat curl \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& chmod +x /rest.sh
EXPOSE 80
CMD /rest.sh
rest.sh
#!/bin/bash
/bin/rm -f out
/usr/bin/mkfifo out
trap "rm -f out" EXIT
while true
do
/bin/cat out | /bin/nc -l 80 > >( # parse the netcat output, to build the answer redirected to the pipe "out".
export REQUEST=
while read line
do
line=$(echo "$line" | tr -d '[\r\n]')
if /bin/echo "$line" | grep -qE '^GET /' # if line starts with "GET /"
then
REQUEST=$(echo "$line" | cut -d ' ' -f2) # extract the request
elif [ "x$line" = x ] # empty line / end of request
then
HTTP_200="HTTP/1.1 200 OK"
HTTP_LOCATION="Location:"
HTTP_404="HTTP/1.1 404 Not Found"
# call a script here
# Note: REQUEST is exported, so the script can parse it (to answer 200/403/404 status code + content)
if echo $REQUEST | grep -qE '^/echo/'
then
printf "%s\n%s %s\n\n%s\n" "$HTTP_200" "$HTTP_LOCATION" $REQUEST ${REQUEST#"/echo/"} > out
elif echo $REQUEST | grep -qE '^/date'
then
date > out
elif echo $REQUEST | grep -qE '^/stats'
then
vmstat -S M > out
elif echo $REQUEST | grep -qE '^/net'
then
ifconfig > out
else
printf "%s\n%s %s\n\n%s\n" "$HTTP_404" "$HTTP_LOCATION" $REQUEST "Resource $REQUEST NOT FOUND!" > out
fi
fi
done
)
done
docker build -t ncimange .
docker run -d -i -p 80:80 --name ncrest ncimange
docker container ls
IMAGE COMMAND CREATED STATUS PORTS NAMES
ncimange "/bin/sh -c /rest.sh" 8 seconds ago Up 2 seconds 0.0.0.0:80->80/tcp ncrest
docker ps
IMAGE COMMAND CREATED STATUS PORTS NAMES
ncimange "/bin/sh -c /rest.sh" 41 seconds ago Up 34 seconds 0.0.0.0:80->80/tcp ncrest
docker logs ncrest
空
curl -i http://127.0.0.1:80/date
curl: (56) Recv failure: Connection reset by peer
docker exec -it ncrest /bin/bash
netstat -an|grep LISTEN
tcp 0 0 0.0.0.0:41783 0.0.0.0:* LISTEN
curl -i http://127.0.0.1:80/date
curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused
curl -i http://127.0.0.1:41783/date
curl: (56) Recv failure: Connection reset by peer
如何连接到Netcat Rest Docker容器?
最佳答案
您正在安装“错误的” netcat。 Debian有两个netcat软件包:netcat-traditional
和netcat-openbsd
,两者略有不同。 netcat
包是netcat-traditional
的别名。
例如,在您的情况下,您的nc命令应为nc -l -p 80
,因为nc -l 80
仅适用于netcat-openbsd
。
tl; dr:如果您希望使用未修改的脚本,请安装netcat-openbsd
而不是ǹetcat
。
关于bash - 如何连接到在Docker容器中运行的Netcat?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58920615/