Skip to content

Instantly share code, notes, and snippets.

@peczenyj
Created May 9, 2026 12:19
Show Gist options
  • Select an option

  • Save peczenyj/a33bb8ed3d364be6a0f8cec0fa475e76 to your computer and use it in GitHub Desktop.

Select an option

Save peczenyj/a33bb8ed3d364be6a0f8cec0fa475e76 to your computer and use it in GitHub Desktop.
start image and browser on random port
#!/bin/bash
IMAGE="nginx:latest"
CONTAINER_PORT=80
CONTAINER_NAME="my-web-app"
docker rm -f "$CONTAINER_NAME" 2>/dev/null
# -p with only container port = Docker picks a random free host port
docker run -d --name "$CONTAINER_NAME" -p ${CONTAINER_PORT} "$IMAGE"
# Ask Docker which port it assigned
HOST_PORT=$(docker port "$CONTAINER_NAME" ${CONTAINER_PORT}/tcp | head -n1 | cut -d: -f2)
URL="http://localhost:${HOST_PORT}/index.html"
echo "Server running on port $HOST_PORT"
# Wait until reachable
for i in {1..30}; do
if curl -s -o /dev/null -w "%{http_code}" "$URL" | grep -q "200"; then
break
fi
sleep 0.5
done
case "$(uname -s)" in
Darwin) open -a "Google Chrome" "$URL" ;;
Linux) google-chrome "$URL" 2>/dev/null || xdg-open "$URL" ;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment