Possible timing issue pushing to swarm private registry

I see an apparent timing issue when pushing to a private registry in docker-machine. If I keep the sleep in the script then it seems to work consistently but if it is disabled, the docker push results in

Put http://localhost:5000/v1/repositories/registry/: dial tcp 127.0.0.1:5000: getsockopt: connection refused

#!/bin/sh
#set -e

_start_swarm() {
	swarmprefix=$1
	boxcount=$2
	docker-machine create \
		-d virtualbox \
		$swarmprefix-master || _error_exit "cannot create docker machine master"

	swarm_master_ip=$(docker-machine ip $swarmprefix-master)
	eval $(docker-machine env $swarmprefix-master)

	docker swarm init \
		--advertise-addr $swarm_master_ip \
		--listen-addr $swarm_master_ip:2377 || _error_exit "cannot init swarm"

	TOKEN=$(docker swarm join-token -q worker)

	for i in $(seq 0 $boxcount); do
		boxname=$swarmprefix-worker$i
		docker-machine create \
			-d virtualbox \
			$boxname || _error_exit "cannot create docker machine worker0"
		eval $(docker-machine env $boxname)
		docker swarm join --token $TOKEN $swarm_master_ip:2377 || _error_exit "cannot join swarm"
	done

	eval $(docker-machine env $swarmprefix-master)
	docker service create --name registry --publish 5000:5000 registry:2.6

	docker-machine ssh $swarmprefix-master "docker pull registry:2.6"
	docker-machine ssh $swarmprefix-master "docker tag registry:2.6 localhost:5000/registry:2.6"
	# if this sleep isn't here, consistently get "Failed to connect to localhost port 5000: Connection refused."
	#sleep 5
	docker-machine ssh $swarmprefix-master "docker push localhost:5000/registry:2.6"
	docker-machine ssh $swarmprefix-master "curl localhost:5000/v2/_catalog"
}

_test_swarm() {
	swarmprefix=$1
	boxcount=$2
	for i in $(seq 0 $boxcount); do
		docker-machine ssh $swarmprefix-worker$i "curl localhost:5000/v2/_catalog"
	done
}

_clean_swarm() {
	swarmprefix=$1
	boxcount=$2
	if docker-machine ls -q | grep "$swarmprefix-master"; then
		docker-machine rm -y $swarmprefix-master
	fi
	for i in $(seq 0 $boxcount); do
		boxname=$swarmprefix-worker$i
		if docker-machine ls -q | grep "$boxname"; then
			docker-machine rm -y $boxname
		fi
	done
}

_error_exit() {
	echo "$1" 1>&2
	exit 1
}

print_help_and_exit() {
	echo "Usage: $0 <'start' or 'clean'>"
	exit 1
}

if [ "$#" -ne 1 ]; then
	print_help_and_exit
fi

boxcount=5

action="$1"
case $action in
	start)
		_start_swarm build 1
		;;
	test)
		_test_swarm build 1
		;;
	clean)
		_clean_swarm build 1
		;;
esac