Created
May 9, 2026 12:19
-
-
Save peczenyj/a33bb8ed3d364be6a0f8cec0fa475e76 to your computer and use it in GitHub Desktop.
start image and browser on random port
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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