You may think that petting a dog seems so simple. However, did you know that the wrong kind of petting can actually make a dog nervous or scared?
When you see a stray dog or someone else's dog whom you don't know, it's very important that you don't scare him away as you approach. A huge mistake that many people make is that when they see the dog backing up or moving away, they follow after them to try to pet it. The first step, however, is to make sure that you look as non-threatening as possible. So crouch down so that you are more eye level with the dog. Don't bend and tower over them as dogs may take that as a sign of dominance and it may threaten them. Squat down, extend your hand, and wait for the dog to come to you. If they come forward wagging their tail, you can pet him. If the dog backs off or pulls his head away from you, it may be best to just leave it alone.
Even when the dog you're meeting for the first time seems friendly, follow the same step as above. Look as non-threatening as possible, squat & bend down, extend your hand, and wait for the dog to come to you. Make sure your body language tells the dog that you are also relaxed. If you have treats on hand that's even better! You can first try to offer them treats and if they come over to you, then the dog may be more likely to let you pet them.
Make sure to follow some rules prior to petting your dog. Some rules include making sure your dog sits down before you pet him or never petting your dog if they are jumping at you. In this way you can make sure that you aren't actually reinforcing any of your dog's impolite, bad, or potentially harmful behavior. Although your dog may be doing it purely out of excitement and with no ill intentions, jumping onto people can be dangerous as it can knock people over or cause them to trip. Make sure that if there are kids in the house that they avoid pulling on your dog's ears, giving too tight of a hug, or trying to ride or jump on their backs - some dogs may not like it. Even if it's your own dog, remember to also give it the personal space it needs.