It does this by looking for little markers called antigens. Think of antigens as being little uniforms. All the cells in your body wear the same uniform, even though they may have different functions. Microbes coming into the body have their own uniforms, which are usually very different. Maybe they're even dressed in civvies, who knows.
Guard cells patrol the body all the time.
They also patrol the body tissues. Microphages are cells with powerful digestive enzymes and antibacterial substances. When a microphage sees a foreign uniform, it rushes over with a baton, bangs the microbe over the head and then gobbles it up to get rid of it. They are always first at the scene of the crime, and call for reinforcements from more powerful immune cells. It's quite possible that the microbes may be more powerful than the microphages, in which case it's the microphage that gets shot before it can wield the baton.