Scaling a service
Now, let's, for a moment, assume that our sample application has been live on the web and become very successful. Loads of people want to see our cute animal images. So now we're facing a problem since our application has started to slow down. To counteract this problem, we want to run multiple instances of the web service. With Docker Compose, this is readily done.
Running more instances is also called scaling up. We can use this tool to scale our web service up to, say, three instances:
$ docker-compose up --scale web=3
If we do this, we are in for a surprise. The output will look similar to the following screenshot:

The second and third instances of the web service fail to start. The error message tells us why: we cannot use the same host port more than once. When instances 2 and 3 try to start, Docker realizes that port 3000 is already taken by the first instance. What can we do? Well, we can just let Docker decide which host port to use for each instance.
If, in the ports section of the compose file, we only specify the container port and leave out the host port, then Docker automatically selects an ephemeral port. Let's do exactly this:
- First, let's tear down the application:
$ docker-compose down
- Then, we modify the docker-compose.yml file to look as follows:
version: "3.5"
services:
web:
image: fundamentalsofdocker/ch08-web:1.0
ports:
- 3000
db:
image: fundamentalsofdocker/ch08-db:1.0
volumes:
- pets-data:/var/lib/postgresql/data
volumes:
pets-data:
- Now, we can start the application again and scale it up immediately after that:
$ docker-compose up -d
$ docker-compose scale web=3
Starting ch08_web_1 ... done
Creating ch08_web_2 ... done
Creating ch08_web_3 ... done
- If we now do a docker-compose ps, we should see the following screenshot:

- As we can see, each service has been associated to a different host port. We can try to see whether they work, for example, using curl. Let's test the third instance, ch08_web_3:
$ curl -4 localhost:32770
Pets Demo Application
The answer, Pets Demo Application, tells us that, indeed, our application is still working as expected. Try it out for the other two instances to be sure.