Service discovery is detecting the services within a computer network: knowing on which IP and port each one runs. In a monolith, the parts call each other with methods of the same program, so it isn't needed. With microservices, each service runs in several instances on different machines, and someone has to know where each one is. It's like a company phone directory: you don't know the extension of all 200 people by heart, you look it up.
With microservices on virtual machines or containers, the number of instances and their addresses change all the time: autoscaling adds 5 instances in the morning and removes them at night, and one that crashes comes back with another IP. That's why instances are ephemeral, and writing IPs by hand in the configuration doesn't work. You need a mechanism that tracks that changing set. It's like looking for a food truck: each day it's on another corner, so you check the app to see where it is today.
There are 2 patterns. In client-side discovery, the client asks the service registry where the other service is and calls it directly. In server-side discovery, the client calls an intermediary, like a load balancer, which checks the registry and forwards the request to an available instance. It's like getting a taxi: either you look up a driver's number on the list yourself (client), or you call the dispatcher and they send you one (server).
A service registry is a database with the network addresses of each service's instances, which clients can call. It must be highly available, because if it goes down, nobody finds anybody, and always up to date, because an old address sends requests to a dead instance. Common tools are etcd, Consul and Apache Zookeeper. It's like an airport arrivals board: if it shows old data or goes dark, everyone goes to the wrong gate.
Instances get into the registry in 2 ways. With self-registration, each instance registers on startup, removes itself on shutdown and sends heartbeats, for example every 10 seconds, to stay listed. With third-party registration, the registry watches the environment, by polling it or subscribing to events, and records new instances and removes terminated ones. It's like class attendance: either each student signs the sheet, or the teacher takes roll themselves.
Communication between services is essential, but as they grow, for example from 5 to 200 services, routing it becomes very complex. A service mesh makes that communication managed, observable and secure, and works together with service discovery to find the services. Istio and Envoy are among the most used. It's like an airport's air traffic control: planes don't coordinate among themselves, a tower orders all the traffic.